Українська
Сховища, що застосовують події
Крок 1. Список чатів слідує за подіями
Навіщо. Список чатів має реагувати майже на кожну подію (табл. 20.1). Сховище підписується на потік подій один раз, у конструкторі, а метод apply(event) з одним switch їх обробляє – той самий шаблон, що й у редюсера: надходить подія, стан змінюється, екран слідує за ним.
Таблиця 20.1. Як ChatsStore застосовує події хаба
| Подія | Вплив на список |
|---|---|
messageCreated | чат переходить нагору з новим останнім повідомленням; лічильник непрочитаного зростає, окрім власних повідомлень користувача й відкритого видимого чату; невідомий чат (хтось почав із нами особистий чат) запускає перезавантаження |
messageUpdated | попередній перегляд змінюється, якщо це було останнє повідомлення |
messageDeleted | попередній перегляд показує «Message deleted», якщо це було останнє повідомлення |
membersAdded | якщо додали користувача: перезавантажити список (новий чат); інакше оновити подробиці відкритого чату (кількість учасників) |
memberRemoved | якщо видалили користувача: прибрати чат і оголосити про це через removed; інакше оновити подробиці |
chatUpdated | забути кешований аватар чату й перезавантажити подробиці (назву, псевдонім, ролі) |
chatDeleted | прибрати чат і оголосити про це |
Що зробити. Доповніть ChatsStore (нові рядки зеленим). Тепер він остаточний:
ts
import { Injectable, computed, effect, inject, signal } from '@angular/core';
import { Subject, firstValueFrom } from 'rxjs';
import { ChatsApi, avatarUrl } from '../core/api/chatex-api';
import { ChatDto, ChatListItemDto, LastMessageDto, MessageDto } from '../core/api/models';
import { AuthService } from '../core/auth/auth.service';
import { BlobUrlService } from '../core/media/blob-url.service';
import { HubEvent, RealtimeService } from '../core/realtime/realtime.service';
/** A chat list row; `lastMessage.deleted` is set locally when the last message gets deleted. */
export type ChatListItem = ChatListItemDto & {
lastMessage?: (LastMessageDto & { deleted?: boolean; hasAttachments?: boolean }) | null;
};
const byActivity = (a: ChatListItem, b: ChatListItem) =>
a.lastActivityAt < b.lastActivityAt ? 1 : a.lastActivityAt > b.lastActivityAt ? -1 : 0;
/** The user's chats (most recently active first), kept current by hub events. */
@Injectable({ providedIn: 'root' })
export class ChatsStore {
private readonly api = inject(ChatsApi);
private readonly auth = inject(AuthService);
private readonly blobs = inject(BlobUrlService);
private nextCursor: string | null = null;
private reloadTimer: ReturnType<typeof setTimeout> | undefined;
readonly items = signal<ChatListItem[]>([]);
readonly loaded = signal(false);
readonly loading = signal(false);
readonly loadingMore = signal(false);
readonly hasMore = signal(false);
/** Full details of chats that were opened, by id. */
readonly details = signal<Readonly<Record<string, ChatDto>>>({});
/** The chat on screen; its new messages don't count as unread. */
readonly activeChatId = signal<string | null>(null);
/** Fires when the user loses access to a chat (deleted, removed, left). */
readonly removed = new Subject<string>();
readonly totalUnread = computed(() =>
this.items().reduce((sum, chat) => sum + (chat.isMuted ? 0 : chat.unreadCount), 0),
);
constructor() {
const realtime = inject(RealtimeService);
realtime.events.subscribe((event) => this.apply(event));
realtime.connected.subscribe(({ reconnected }) => {
if (reconnected && this.loaded()) {
void this.loadFirst();
}
});
effect(() => {
this.auth.sessionEpoch();
this.reset();
});
}
async loadFirst(): Promise<void> {
this.loading.set(true);
try {
const page = await firstValueFrom(this.api.list());
this.items.set([...page.items].sort(byActivity));
this.nextCursor = page.nextCursor ?? null;
this.hasMore.set(!!this.nextCursor);
this.loaded.set(true);
} finally {
this.loading.set(false);
}
}
async loadMore(): Promise<void> {
if (!this.nextCursor || this.loadingMore()) {
return;
}
this.loadingMore.set(true);
try {
const page = await firstValueFrom(this.api.list(this.nextCursor));
const known = new Set(this.items().map((c) => c.id));
this.items.update((list) => [...list, ...page.items.filter((c) => !known.has(c.id))]);
this.nextCursor = page.nextCursor ?? null;
this.hasMore.set(!!this.nextCursor);
} finally {
this.loadingMore.set(false);
}
}
/** Loads (or reloads) a chat's details and syncs its list row. */
async loadChat(chatId: string): Promise<ChatDto> {
const chat = await firstValueFrom(this.api.get(chatId));
this.setDetails(chat);
return chat;
}
/** Stores fresh chat details (from any API response) and patches the list row. */
setDetails(chat: ChatDto): void {
const previous = this.details()[chat.id];
if (previous && previous.hasAvatar !== chat.hasAvatar) {
this.blobs.invalidate(avatarUrl.chat(chat.id));
}
this.details.update((all) => ({ ...all, [chat.id]: chat }));
if (!chat.myRole) {
this.items.update((list) => list.filter((c) => c.id !== chat.id));
return;
}
const role = chat.myRole;
const exists = this.items().some((c) => c.id === chat.id);
if (exists) {
this.patch(chat.id, (c) => ({
...c,
title: chat.title,
hasAvatar: chat.hasAvatar,
isMuted: chat.isMuted,
myRole: role,
peer: chat.peer,
}));
} else {
const item: ChatListItem = {
id: chat.id,
type: chat.type,
title: chat.title,
hasAvatar: chat.hasAvatar,
lastActivityAt: new Date().toISOString(),
myRole: role,
isMuted: chat.isMuted,
lastMessage: null,
unreadCount: 0,
peer: chat.peer,
};
this.items.update((list) => [item, ...list]);
}
}
/**
* Forget a chat the user can no longer see. `notify` announces it on `removed` (the open
* conversation then closes with a notice); pass false when the user left or deleted it here.
*/
remove(chatId: string, notify = true): void {
this.items.update((list) => list.filter((c) => c.id !== chatId));
this.details.update((all) => {
const next = { ...all };
delete next[chatId];
return next;
});
if (notify) {
this.removed.next(chatId);
}
}
markReadLocally(chatId: string): void {
this.patch(chatId, (c) => (c.unreadCount ? { ...c, unreadCount: 0 } : c));
}
setMuted(chatId: string, muted: boolean): void {
this.patch(chatId, (c) => ({ ...c, isMuted: muted }));
const chat = this.details()[chatId];
if (chat) {
this.details.update((all) => ({ ...all, [chatId]: { ...chat, isMuted: muted } }));
}
}
/** Keeps the list in step with a message the user just sent. */
noteOwnMessage(message: MessageDto): void {
this.applyMessageCreated(message);
}
private apply(event: HubEvent): void {
const me = this.auth.user()?.id;
switch (event.type) {
case 'messageCreated':
this.applyMessageCreated(event.message);
break;
case 'messageUpdated':
this.patch(event.message.chatId, (c) =>
c.lastMessage?.id === event.message.id
? { ...c, lastMessage: { ...c.lastMessage, body: event.message.body ?? '' } }
: c,
);
break;
case 'messageDeleted':
this.patch(event.chatId, (c) =>
c.lastMessage?.id === event.messageId
? { ...c, lastMessage: { ...c.lastMessage, body: '', deleted: true } }
: c,
);
break;
case 'membersAdded':
if (me && event.userIds.includes(me)) {
this.scheduleReload();
} else if (this.details()[event.chatId]) {
void this.loadChat(event.chatId).catch(() => undefined);
}
break;
case 'memberRemoved':
if (event.userId === me) {
this.remove(event.chatId);
} else if (this.details()[event.chatId]) {
void this.loadChat(event.chatId).catch(() => undefined);
}
break;
case 'chatUpdated':
this.blobs.invalidate(avatarUrl.chat(event.chatId));
void this.loadChat(event.chatId).catch(() => undefined);
break;
case 'chatDeleted':
this.remove(event.chatId);
break;
}
}
private applyMessageCreated(message: MessageDto): void {
const chat = this.items().find((c) => c.id === message.chatId);
if (!chat) {
// A chat we don't have yet (e.g. someone started a direct chat with us).
this.scheduleReload();
return;
}
if (chat.lastMessage && chat.lastMessage.id >= message.id) {
return;
}
const mine = message.sender.id === this.auth.user()?.id;
const visible =
this.activeChatId() === message.chatId && document.visibilityState === 'visible';
this.items.update((list) =>
list
.map((c) =>
c.id === message.chatId
? {
...c,
lastActivityAt: message.createdAt,
lastMessage: {
id: message.id,
senderId: message.sender.id,
body: (message.body ?? '').slice(0, 100),
createdAt: message.createdAt,
hasAttachments: message.attachments.length > 0,
},
unreadCount: mine || visible ? c.unreadCount : c.unreadCount + 1,
}
: c,
)
.sort(byActivity),
);
}
private patch(chatId: string, change: (chat: ChatListItem) => ChatListItem): void {
this.items.update((list) => list.map((c) => (c.id === chatId ? change(c) : c)));
}
private scheduleReload(): void {
clearTimeout(this.reloadTimer);
this.reloadTimer = setTimeout(() => void this.loadFirst().catch(() => undefined), 300);
}
private reset(): void {
clearTimeout(this.reloadTimer);
this.items.set([]);
this.details.set({});
this.loaded.set(false);
this.hasMore.set(false);
this.nextCursor = null;
this.activeChatId.set(null);
}
}realtime.events.subscribe((event) => this.apply(event))– сховище є кореневим singleton, тож підписка живе, доки живе застосунок; відписуватися не потрібно.switch (event.type)звужує об’єднання в кожномуcase:event.messageіснує після'messageCreated',event.userIds– після'membersAdded'. Події, що сховищу не цікаві (набір тексту, присутність), проходять крізьswitch.- Дублікати нешкідливі.
applyMessageCreatedігнорує повідомлення, ідентифікатор якого не новіший за останнє в рядку (chat.lastMessage.id >= message.id). Вкладка відправника отримує своє повідомлення двічі – зnoteOwnMessageпісляPOSTі від хаба – і враховує його один раз. - Правило непрочитаного порівнює відправника з користувачем, що увійшов, і перевіряє
activeChatIdтаdocument.visibilityState: повідомлення в чаті, на який дивиться користувач, не є непрочитаним, а те саме повідомлення в прихованій вкладці браузера – є. scheduleReload()згладжує перезавантаження на 300 мс (debounce), тож серія подій (користувача додали одразу в п’ять чатів) коштує один запит.- Після перепідключення сховище перезавантажує першу сторінку чатів, якщо вона вже була завантажена: лічильники непрочитаного й останні повідомлення могли змінитися, поки клієнт був поза мережею.
Крок 2. Розмова слідує за подіями
Навіщо. Відкрита розмова потребує чотирьох подій: нові й змінені повідомлення об’єднуються за ідентифікатором через merge з теми 19; видалені стають заповнювачами; messagesRead від інших учасників пересуває їхню позицію прочитання, через що одна позначка стає двома. Після перепідключення сховище отримує все новіше за своє найновіше підтверджене повідомлення через GET /api/chats/{id}/messages?after= (тема 11), сторінка за сторінкою.
Що зробити. Доповніть MessagesStore (нові рядки зеленим). Тепер він остаточний:
ts
import { Injectable, computed, inject, signal } from '@angular/core';
import { DestroyRef } from '@angular/core';
import { firstValueFrom } from 'rxjs';
import { ChatsApi, MessagesApi } from '../core/api/chatex-api';
import { AttachmentDto, MessageDto, PageDto, compareIds } from '../core/api/models';
import { AuthService } from '../core/auth/auth.service';
import { HubEvent, RealtimeService } from '../core/realtime/realtime.service';
import { ChatsStore } from './chats.store';
/** A message on screen. Messages being sent have `localState` and a temporary id. */
export type ChatMessage = MessageDto & { localState?: 'pending' | 'failed' };
export const PAGE_SIZE = 50;
const CATCH_UP_LIMIT = 100;
let localIds = 0;
/**
* The open chat's messages, oldest first. History is keyset paged (`before=` for older pages,
* `after=` to fill the gap after a reconnect), and hub events are merged in by id so nothing shows
* twice. Provided by the conversation page, so each open chat gets its own instance state.
*/
@Injectable()
export class MessagesStore {
private readonly api = inject(MessagesApi);
private readonly chatsApi = inject(ChatsApi);
private readonly chats = inject(ChatsStore);
private readonly auth = inject(AuthService);
private olderCursor: string | null = null;
/** Bumped on every chat switch so late responses for the previous chat are dropped. */
private generation = 0;
private lastMarkedRead: string | null = null;
readonly chatId = signal<string | null>(null);
readonly messages = signal<ChatMessage[]>([]);
readonly loading = signal(false);
readonly loadingOlder = signal(false);
readonly hasOlder = signal(false);
readonly error = signal<unknown>(null);
/** Read positions of other members, from live MessagesRead events. */
readonly readBy = signal<Readonly<Record<string, string>>>({});
readonly byId = computed(() => new Map(this.messages().map((m) => [m.id, m])));
/** The newest message the server knows about (not a pending one). */
readonly lastConfirmed = computed(() => {
const list = this.messages();
for (let i = list.length - 1; i >= 0; i--) {
if (!list[i].localState) return list[i];
}
return null;
});
/** The newest message that can be a read position (the server rejects deleted ones). */
readonly lastReadable = computed(() => {
const list = this.messages();
for (let i = list.length - 1; i >= 0; i--) {
if (!list[i].localState && !list[i].isDeleted) return list[i];
}
return null;
});
/** The newest message any other member has read. */
readonly peerReadUpTo = computed(() => {
const ids = Object.values(this.readBy());
return ids.length ? ids.reduce((max, id) => (id > max ? id : max)) : null;
});
constructor() {
const realtime = inject(RealtimeService);
const events = realtime.events.subscribe((event) => this.apply(event));
const connected = realtime.connected.subscribe(({ reconnected }) => {
if (reconnected) {
void this.catchUp();
}
});
inject(DestroyRef).onDestroy(() => {
events.unsubscribe();
connected.unsubscribe();
});
}
async open(chatId: string): Promise<void> {
this.generation++;
this.chatId.set(chatId);
this.messages.set([]);
this.readBy.set({});
this.olderCursor = null;
this.hasOlder.set(false);
this.lastMarkedRead = null;
this.error.set(null);
await this.loadInitial();
}
async loadInitial(): Promise<void> {
const chatId = this.chatId();
if (!chatId) {
return;
}
const generation = this.generation;
this.loading.set(true);
try {
const page = await firstValueFrom(this.api.list(chatId, { limit: PAGE_SIZE }));
if (generation !== this.generation) {
return;
}
this.messages.update((current) => merge(current, [...page.items].reverse()));
this.olderCursor = page.nextCursor ?? null;
this.hasOlder.set(!!this.olderCursor);
} catch (error) {
if (generation === this.generation) {
this.error.set(error);
}
} finally {
if (generation === this.generation) {
this.loading.set(false);
}
}
}
async loadOlder(): Promise<void> {
const chatId = this.chatId();
if (!chatId || !this.olderCursor || this.loadingOlder()) {
return;
}
const generation = this.generation;
this.loadingOlder.set(true);
try {
const page = await firstValueFrom(
this.api.list(chatId, { before: this.olderCursor, limit: PAGE_SIZE }),
);
if (generation !== this.generation) {
return;
}
this.messages.update((current) => merge(current, [...page.items].reverse()));
this.olderCursor = page.nextCursor ?? null;
this.hasOlder.set(!!this.olderCursor);
} finally {
if (generation === this.generation) {
this.loadingOlder.set(false);
}
}
}
/** Fetches everything newer than the last message on screen (after a reconnect). */
async catchUp(): Promise<void> {
const chatId = this.chatId();
if (!chatId) {
return;
}
let after = this.lastConfirmed()?.id;
if (!after) {
await this.loadInitial();
return;
}
const generation = this.generation;
for (let i = 0; i < 20 && after; i++) {
const page: PageDto<MessageDto> = await firstValueFrom(
this.api.list(chatId, { after, limit: CATCH_UP_LIMIT }),
);
if (generation !== this.generation) {
return;
}
this.messages.update((current) => merge(current, page.items));
after = page.nextCursor ?? undefined;
}
}
/** Sends a message, showing it at once as pending. */
async send(body: string, attachments: AttachmentDto[], replyToMessageId?: string | null) {
const chatId = this.chatId();
const me = this.auth.user();
if (!chatId || !me) {
return;
}
const localId = `local-${++localIds}`;
const pending: ChatMessage = {
id: localId,
chatId,
sender: {
id: me.id,
userName: me.userName,
displayName: me.displayName,
hasAvatar: me.hasAvatar,
},
body,
replyToMessageId: replyToMessageId ?? null,
createdAt: new Date().toISOString(),
isDeleted: false,
attachments,
localState: 'pending',
};
this.messages.update((list) => [...list, pending]);
await this.deliver(pending);
}
/** Sends a failed message again. */
async retry(localId: string): Promise<void> {
const message = this.byId().get(localId);
if (message?.localState === 'failed') {
this.replace(localId, { ...message, localState: 'pending' });
await this.deliver(message);
}
}
discard(localId: string): void {
this.messages.update((list) => list.filter((m) => m.id !== localId));
}
async edit(messageId: string, body: string): Promise<void> {
const updated = await firstValueFrom(this.api.edit(messageId, body));
this.upsert(updated);
}
async delete(messageId: string): Promise<void> {
await firstValueFrom(this.api.delete(messageId));
this.markDeleted(messageId);
}
/** Moves the read position to the newest message (once per message). */
async markRead(): Promise<void> {
const chatId = this.chatId();
const last = this.lastReadable();
if (!chatId || !last || last.id === this.lastMarkedRead) {
return;
}
this.lastMarkedRead = last.id;
this.chats.markReadLocally(chatId);
try {
await firstValueFrom(this.chatsApi.markRead(chatId, last.id));
} catch {
this.lastMarkedRead = null;
}
}
private async deliver(pending: ChatMessage): Promise<void> {
const generation = this.generation;
try {
const sent = await firstValueFrom(
this.api.send(pending.chatId, {
body: pending.body || null,
replyToMessageId: pending.replyToMessageId,
attachmentIds: pending.attachments.map((a) => a.id),
}),
);
if (generation !== this.generation) {
return;
}
// The hub event may have arrived first; either way keep exactly one copy.
this.messages.update((list) =>
merge(
list.filter((m) => m.id !== pending.id),
[sent],
),
);
this.chats.noteOwnMessage(sent);
} catch (error) {
if (generation === this.generation) {
this.replace(pending.id, { ...pending, localState: 'failed' });
}
throw error;
}
}
private apply(event: HubEvent): void {
const chatId = this.chatId();
switch (event.type) {
case 'messageCreated':
case 'messageUpdated':
if (event.message.chatId === chatId) {
this.upsert(event.message);
}
break;
case 'messageDeleted':
if (event.chatId === chatId) {
this.markDeleted(event.messageId);
}
break;
case 'messagesRead':
if (event.chatId === chatId && event.userId !== this.auth.user()?.id) {
this.readBy.update((all) =>
(all[event.userId] ?? '') >= event.lastReadMessageId
? all
: { ...all, [event.userId]: event.lastReadMessageId },
);
}
break;
}
}
private upsert(message: MessageDto): void {
this.messages.update((list) => merge(list, [message]));
}
private replace(id: string, message: ChatMessage): void {
this.messages.update((list) => list.map((m) => (m.id === id ? message : m)));
}
private markDeleted(messageId: string): void {
this.messages.update((list) =>
list.map((m) =>
m.id === messageId ? { ...m, isDeleted: true, body: null, attachments: [] } : m,
),
);
}
}
/**
* Merges server messages into the list: replaces ones with the same id, keeps confirmed messages
* ordered by id, and keeps pending messages at the end.
*/
export function merge(current: ChatMessage[], incoming: MessageDto[]): ChatMessage[] {
if (!incoming.length) {
return current;
}
const confirmed = new Map(current.filter((m) => !m.localState).map((m) => [m.id, m]));
for (const message of incoming) {
confirmed.set(message.id, message);
}
const pending = current.filter((m) => m.localState);
return [...[...confirmed.values()].sort((a, b) => compareIds(a.id, b.id)), ...pending];
}- Це сховище не є singleton: воно живе, доки живе сторінка його розмови.
inject(DestroyRef).onDestroy(...)скасовує обидві підписки, коли сторінка зникає; без цього кожен відвіданий чат залишав би по собі сховище, яке й далі застосовує події. - Події інших чатів ігноруються (
event.message.chatId === chatId). readByзберігає найновішу позицію прочитання кожного іншого учасника й ніколи не рухає її назад; події прочитання з інших вкладок самого користувача ігноруються.peerReadUpTo– максимум заreadBy– це те, з чим порівнює список повідомлень, щоб показати «seen».catchUp()просить до 100 повідомленьafterнайновішого підтвердженого й іде заnextCursorщонайбільше 20 сторінок. Якщо в розмові повідомлень не було, він просто завантажує першу сторінку. Перевірка покоління відкидає результат, якщо користувач тим часом перемкнув чат.
Рис. 20.2 показує перепідключення з погляду сховища.
Рис. 20.2. Надолужування після перепідключення
Крок 3. Тестування подій
Що зробити. Замініть обидві специфікації їхніми остаточними версіями; тепер вони використовують fakeRealtime() і подають події в сховища:
ts
import { TestBed } from '@angular/core/testing';
import { of } from 'rxjs';
import { BOB, ME, fakeAuth, fakeRealtime, message, messageId } from '../../testing/fakes';
import { ChatsApi } from '../core/api/chatex-api';
import { ChatListItemDto } from '../core/api/models';
import { AuthService } from '../core/auth/auth.service';
import { BlobUrlService } from '../core/media/blob-url.service';
import { RealtimeService } from '../core/realtime/realtime.service';
import { ChatsStore } from './chats.store';
function item(
id: string,
lastActivityAt: string,
overrides: Partial<ChatListItemDto> = {},
): ChatListItemDto {
return {
id,
type: 'group',
title: id,
hasAvatar: false,
lastActivityAt,
myRole: 'member',
isMuted: false,
lastMessage: null,
unreadCount: 0,
peer: null,
...overrides,
};
}
describe('ChatsStore', () => {
let store: ChatsStore;
let realtime: ReturnType<typeof fakeRealtime>;
beforeEach(async () => {
Object.defineProperty(document, 'visibilityState', { value: 'visible', configurable: true });
realtime = fakeRealtime();
const api = {
list: vi.fn(() =>
of({
items: [
item('chat-old', '2026-11-01T00:00:00Z'),
item('chat-1', '2026-11-05T00:00:00Z'),
item('chat-muted', '2026-11-03T00:00:00Z', { isMuted: true, unreadCount: 4 }),
],
nextCursor: null,
}),
),
};
TestBed.configureTestingModule({
providers: [
{ provide: ChatsApi, useValue: api },
{ provide: AuthService, useValue: fakeAuth() },
{ provide: BlobUrlService, useValue: { invalidate: vi.fn() } },
{ provide: RealtimeService, useValue: realtime },
],
});
store = TestBed.inject(ChatsStore);
TestBed.tick();
await store.loadFirst();
});
const order = () => store.items().map((c) => c.id);
const get = (id: string) => store.items().find((c) => c.id === id)!;
it('lists chats by latest activity', () => {
expect(order()).toEqual(['chat-1', 'chat-muted', 'chat-old']);
});
it('moves a chat with a new message to the top and counts it unread', () => {
realtime.events.next({
type: 'messageCreated',
message: message(10, { chatId: 'chat-old', createdAt: '2026-11-10T00:00:00Z' }),
});
expect(order()[0]).toBe('chat-old');
expect(get('chat-old').unreadCount).toBe(1);
expect(get('chat-old').lastMessage?.id).toBe(messageId(10));
});
it("doesn't count the user's own messages or the open chat as unread", () => {
store.activeChatId.set('chat-old');
realtime.events.next({ type: 'messageCreated', message: message(11, { chatId: 'chat-old' }) });
realtime.events.next({
type: 'messageCreated',
message: message(12, { chatId: 'chat-1', sender: { ...BOB, id: ME.id } }),
});
expect(get('chat-old').unreadCount).toBe(0);
expect(get('chat-1').unreadCount).toBe(0);
});
it('leaves muted chats out of the total unread count', () => {
realtime.events.next({ type: 'messageCreated', message: message(13, { chatId: 'chat-1' }) });
expect(store.totalUnread()).toBe(1);
});
it('marks the last message deleted', () => {
realtime.events.next({ type: 'messageCreated', message: message(14, { chatId: 'chat-1' }) });
realtime.events.next({ type: 'messageDeleted', chatId: 'chat-1', messageId: messageId(14) });
expect(get('chat-1').lastMessage).toMatchObject({ deleted: true, body: '' });
});
it('drops chats that were deleted or that the user was removed from', () => {
const removed: string[] = [];
store.removed.subscribe((id) => removed.push(id));
realtime.events.next({ type: 'chatDeleted', chatId: 'chat-1' });
realtime.events.next({ type: 'memberRemoved', chatId: 'chat-old', userId: ME.id });
realtime.events.next({ type: 'memberRemoved', chatId: 'chat-muted', userId: BOB.id });
expect(order()).toEqual(['chat-muted']);
expect(removed).toEqual(['chat-1', 'chat-old']);
});
it('clears unread counts locally', () => {
store.markReadLocally('chat-muted');
expect(get('chat-muted').unreadCount).toBe(0);
});
});ts
import { TestBed } from '@angular/core/testing';
import { Subject, of, throwError } from 'rxjs';
import { BOB, ME, fakeAuth, fakeRealtime, message, messageId, settle } from '../../testing/fakes';
import { ChatsApi, MessagesApi } from '../core/api/chatex-api';
import { MessageDto, PageDto } from '../core/api/models';
import { AuthService } from '../core/auth/auth.service';
import { RealtimeService } from '../core/realtime/realtime.service';
import { ChatsStore } from './chats.store';
import { MessagesStore, merge } from './messages.store';
describe('MessagesStore', () => {
let store: MessagesStore;
let realtime: ReturnType<typeof fakeRealtime>;
let api: {
list: ReturnType<typeof vi.fn>;
send: ReturnType<typeof vi.fn>;
edit: ReturnType<typeof vi.fn>;
delete: ReturnType<typeof vi.fn>;
};
let chats: {
markReadLocally: ReturnType<typeof vi.fn>;
noteOwnMessage: ReturnType<typeof vi.fn>;
};
let chatsApi: { markRead: ReturnType<typeof vi.fn> };
const page = (items: MessageDto[], nextCursor: string | null = null): PageDto<MessageDto> => ({
items,
nextCursor,
});
const ids = () => store.messages().map((m) => m.id);
beforeEach(() => {
realtime = fakeRealtime();
api = { list: vi.fn(), send: vi.fn(), edit: vi.fn(), delete: vi.fn() };
chats = { markReadLocally: vi.fn(), noteOwnMessage: vi.fn() };
chatsApi = { markRead: vi.fn(() => of(undefined)) };
TestBed.configureTestingModule({
providers: [
MessagesStore,
{ provide: MessagesApi, useValue: api },
{ provide: ChatsApi, useValue: chatsApi },
{ provide: ChatsStore, useValue: chats },
{ provide: AuthService, useValue: fakeAuth() },
{ provide: RealtimeService, useValue: realtime },
],
});
store = TestBed.inject(MessagesStore);
});
async function openWith(newestFirst: MessageDto[], cursor: string | null = null) {
api.list.mockReturnValueOnce(of(page(newestFirst, cursor)));
await store.open('chat-1');
}
it('shows the newest page oldest first', async () => {
await openWith([message(3), message(2), message(1)], 'cursor-1');
expect(api.list).toHaveBeenCalledWith('chat-1', { limit: 50 });
expect(ids()).toEqual([messageId(1), messageId(2), messageId(3)]);
expect(store.hasOlder()).toBe(true);
});
it('prepends older pages using the cursor', async () => {
await openWith([message(4), message(3)], 'cursor-1');
api.list.mockReturnValueOnce(of(page([message(2), message(1)])));
await store.loadOlder();
expect(api.list).toHaveBeenLastCalledWith('chat-1', { before: 'cursor-1', limit: 50 });
expect(ids()).toEqual([1, 2, 3, 4].map(messageId));
expect(store.hasOlder()).toBe(false);
});
it('adds live messages once and ignores other chats', async () => {
await openWith([message(1)]);
realtime.events.next({ type: 'messageCreated', message: message(2) });
realtime.events.next({ type: 'messageCreated', message: message(2) });
realtime.events.next({ type: 'messageCreated', message: message(3, { chatId: 'other' }) });
expect(ids()).toEqual([messageId(1), messageId(2)]);
});
it('applies edits and deletions from the hub', async () => {
await openWith([message(2), message(1)]);
realtime.events.next({
type: 'messageUpdated',
message: message(1, { body: 'edited', editedAt: '2026-11-10T12:05:00Z' }),
});
realtime.events.next({ type: 'messageDeleted', chatId: 'chat-1', messageId: messageId(2) });
const [first, second] = store.messages();
expect(first.body).toBe('edited');
expect(second.isDeleted).toBe(true);
expect(second.body).toBeNull();
});
it('shows a sent message at once and swaps in the server copy', async () => {
await openWith([message(1)]);
const response = new Subject<MessageDto>();
api.send.mockReturnValueOnce(response);
const sending = store.send('hello', []);
expect(store.messages().at(-1)).toMatchObject({ body: 'hello', localState: 'pending' });
const sent = message(2, {
body: 'hello',
sender: { ...BOB, id: ME.id, displayName: ME.displayName },
});
response.next(sent);
response.complete();
await sending;
expect(ids()).toEqual([messageId(1), messageId(2)]);
expect(store.messages().some((m) => m.localState)).toBe(false);
expect(chats.noteOwnMessage).toHaveBeenCalledWith(sent);
});
it('keeps one copy when the hub event beats the POST response', async () => {
await openWith([message(1)]);
const response = new Subject<MessageDto>();
api.send.mockReturnValueOnce(response);
const sent = message(2, { body: 'hi' });
const sending = store.send('hi', []);
realtime.events.next({ type: 'messageCreated', message: sent });
response.next(sent);
response.complete();
await sending;
expect(ids()).toEqual([messageId(1), messageId(2)]);
});
it('marks a message failed when sending fails, and can retry it', async () => {
await openWith([]);
api.send.mockReturnValueOnce(throwError(() => new Error('offline')));
await expect(store.send('hi', [])).rejects.toThrow('offline');
const failed = store.messages()[0];
expect(failed.localState).toBe('failed');
api.send.mockReturnValueOnce(of(message(5, { body: 'hi' })));
await store.retry(failed.id);
expect(ids()).toEqual([messageId(5)]);
});
it('catches up after a reconnect by following the after cursor', async () => {
await openWith([message(1)]);
api.list
.mockReturnValueOnce(of(page([message(2), message(3)], 'next')))
.mockReturnValueOnce(of(page([message(4)], null)));
realtime.connected.next({ reconnected: true });
await settle();
expect(api.list).toHaveBeenCalledWith('chat-1', { after: messageId(1), limit: 100 });
expect(api.list).toHaveBeenCalledWith('chat-1', { after: 'next', limit: 100 });
expect(ids()).toEqual([1, 2, 3, 4].map(messageId));
});
it('marks the newest message read once', async () => {
await openWith([message(2), message(1)]);
await store.markRead();
await store.markRead();
expect(chatsApi.markRead).toHaveBeenCalledTimes(1);
expect(chatsApi.markRead).toHaveBeenCalledWith('chat-1', messageId(2));
expect(chats.markReadLocally).toHaveBeenCalledWith('chat-1');
});
it('never uses a deleted message as the read position', async () => {
await openWith([message(2, { isDeleted: true, body: null }), message(1)]);
await store.markRead();
expect(chatsApi.markRead).toHaveBeenCalledWith('chat-1', messageId(1));
});
it('tracks how far other members have read', async () => {
await openWith([message(2), message(1)]);
realtime.events.next({
type: 'messagesRead',
chatId: 'chat-1',
userId: BOB.id,
lastReadMessageId: messageId(2),
});
realtime.events.next({
type: 'messagesRead',
chatId: 'chat-1',
userId: BOB.id,
lastReadMessageId: messageId(1),
});
realtime.events.next({
type: 'messagesRead',
chatId: 'chat-1',
userId: ME.id,
lastReadMessageId: messageId(9),
});
expect(store.peerReadUpTo()).toBe(messageId(2));
});
it('drops responses for a chat that is no longer open', async () => {
const slow = new Subject<PageDto<MessageDto>>();
api.list.mockReturnValueOnce(slow);
const first = store.open('chat-1');
api.list.mockReturnValueOnce(of(page([message(7, { chatId: 'chat-2' })])));
await store.open('chat-2');
slow.next(page([message(1)]));
slow.complete();
await first;
expect(ids()).toEqual([messageId(7)]);
});
});
describe('merge', () => {
it('orders by id and keeps pending messages last', () => {
const pending = { ...message(0), id: 'local-1', localState: 'pending' as const };
const merged = merge([message(3), pending], [message(1), message(3, { body: 'new' })]);
expect(merged.map((m) => m.id)).toEqual([messageId(1), messageId(3), 'local-1']);
expect(merged[1].body).toBe('new');
});
});П’ять нових тестів ChatsStore піднімають чат нагору й рахують його непрочитаним, не враховують власні повідомлення користувача й відкритий чат у лічильнику непрочитаного, не враховують чати з вимкненими сповіщеннями в загальній сумі, позначають видалене останнє повідомлення та прибирають чати, які видалили або з яких видалили користувача.
П’ять нових тестів MessagesStore додають живі повідомлення один раз і ігнорують інші чати, застосовують редагування й видалення, зберігають одну копію, коли подія хаба випереджає відповідь на POST, йдуть за курсором after після перепідключення (await settle() дає змогу виконатися асинхронному catchUp) і відстежують, наскільки далеко дочитали інші учасники.
Перевірка
powershell
npm test -- --watch=false Test Files 8 passed (8)
Tests 48 passed (48)Запустіть API й клієнт та увійдіть як Alice і як Bob у двох вікнах. Надішліть повідомлення від імені Bob: воно одразу з’являється у відкритій розмові Alice, а в її списку – зі значком непрочитаного, якщо відкрито інший чат. Відредагуйте й видаліть його: екран Alice слідує за змінами. Коли Alice прочитає повідомлення Bob, одинарна позначка під ним у вікні Bob стане подвійною.