Skip to content
Open
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
2 changes: 2 additions & 0 deletions package/src/store/OfflineDB.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,8 @@ export class OfflineDB extends AbstractOfflineDB {

deleteMessagesForChannel = api.deleteMessagesForChannel;

deleteMessagesForChannelInRange = api.deleteMessagesForChannelInRange;

dropPendingTasks = api.dropPendingTasks;

hardDeleteMessage = api.deleteMessage;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import type { ChannelStateResponseFields, TimestampNS } from 'stream-chat';

import { generateChannelResponse } from '../../../mock-builders/generator/channel';
import { generateMessage } from '../../../mock-builders/generator/message';
import { BetterSqlite } from '../../../test-utils/BetterSqlite';
import { SqliteClient } from '../../SqliteClient';
import { deleteMessagesForChannelInRange } from '../deleteMessagesForChannelInRange';
import { upsertChannels } from '../upsertChannels';

// unix nanoseconds of minute `minute`, as the messages table stores `createdAt`
const at = (minute: number) => (Date.UTC(2026, 0, 1, 0, minute) * 1e6) as TimestampNS;

describe('deleteMessagesForChannelInRange', () => {
let cid: string;
let otherCid: string;

const storeChannel = async (minutes: number[]) => {
const channelResponse = generateChannelResponse({ members: [], messages: [] });
const channelCid = channelResponse.channel.cid as string;
channelResponse.messages = minutes.map((minute) =>
generateMessage({ cid: channelCid, created_at: at(minute), id: `${channelCid}-m${minute}` }),
) as unknown as typeof channelResponse.messages;
await upsertChannels({
channels: [channelResponse] as unknown as ChannelStateResponseFields[],
isLatestMessagesSet: true,
});
return channelCid;
};

const storedIds = async (channelCid: string) =>
(await BetterSqlite.selectFromTable<{ cid: string; id: string }>('messages'))
.filter((row) => row.cid === channelCid)
.map((row) => row.id.replace(`${channelCid}-`, ''))
.sort();

beforeEach(async () => {
await SqliteClient.initializeDatabase();
await BetterSqlite.openDB();
cid = await storeChannel([1, 2, 3, 4]);
otherCid = await storeChannel([3]);
});

afterEach(() => {
BetterSqlite.dropAllTables();
BetterSqlite.closeDB();
});

it('deletes the messages created after `after` and at or before `upTo`', async () => {
await deleteMessagesForChannelInRange({ after: at(1), cid, upTo: at(3) });

expect(await storedIds(cid)).toEqual(['m1', 'm4']);
});

it('deletes from the first message when there is no `after`', async () => {
await deleteMessagesForChannelInRange({ after: null, cid, upTo: at(2) });

expect(await storedIds(cid)).toEqual(['m3', 'm4']);
});

it('keeps the messages in `keepMessageIds`', async () => {
await deleteMessagesForChannelInRange({
after: at(1),
cid,
keepMessageIds: [`${cid}-m2`, `${cid}-m4`],
upTo: at(4),
});

expect(await storedIds(cid)).toEqual(['m1', 'm2', 'm4']);
});

it("leaves other channels' messages", async () => {
await deleteMessagesForChannelInRange({ after: at(1), cid, upTo: at(4) });

expect(await storedIds(otherCid)).toEqual(['m3']);
});

it('only returns the query with execute=false', async () => {
const queries = await deleteMessagesForChannelInRange({
after: at(1),
cid,
execute: false,
upTo: at(4),
});

expect(queries).toEqual([
[
'DELETE FROM messages WHERE cid = ? AND createdAt > ? AND createdAt <= ?',
[cid, at(1), at(4)],
],
]);
expect(await storedIds(cid)).toEqual(['m1', 'm2', 'm3', 'm4']);
});
});
57 changes: 57 additions & 0 deletions package/src/store/apis/deleteMessagesForChannelInRange.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import type { TimestampNS } from 'stream-chat';

import { SqliteClient } from '../SqliteClient';

/**
* Deletes the channel's messages created after `after` (from the first one when it is not set) and
* at or before `upTo`, as a rewind hides them, except those in `keepMessageIds`. Their reactions go
* with them (`ON DELETE CASCADE`).
*/
export const deleteMessagesForChannelInRange = async ({
after,
cid,
execute = true,
keepMessageIds,
upTo,
}: {
cid: string;
/** Unix nanoseconds, as the API sends it. */
after?: TimestampNS | null;
/** Unix nanoseconds, as the API sends it. */
upTo: TimestampNS;
/** Messages kept even inside the range: the unsent ones, which the server never had. */
keepMessageIds?: string[];
execute?: boolean;
}) => {
// `createdAt` holds unix nanoseconds, so the bounds are too and the comparison is numeric.
const conditions = ['cid = ?'];
const params: (string | number)[] = [cid];
if (after != null) {
conditions.push('createdAt > ?');
params.push(after);
}
conditions.push('createdAt <= ?');
params.push(upTo);
if (keepMessageIds?.length) {
conditions.push(`id NOT IN (${keepMessageIds.map(() => '?').join(', ')})`);
params.push(...keepMessageIds);
}
const query: [string, (string | number)[]] = [
`DELETE FROM messages WHERE ${conditions.join(' AND ')}`,
params,
];

SqliteClient.logger?.('info', 'deleteMessagesForChannelInRange', {
after,
cid,
execute,
keepMessageIds,
upTo,
});

if (execute) {
await SqliteClient.executeSql.apply(null, query);
}

return [query];
};
1 change: 1 addition & 0 deletions package/src/store/apis/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ export * from './deleteChannel';
export * from './deleteMember';
export * from './deleteMessage';
export * from './deleteMessagesForChannel';
export * from './deleteMessagesForChannelInRange';
export * from './getAllChannelIds';
export * from './getAppSettings';
export * from './getChannelMessages';
Expand Down
Loading