Skip to content

Commit 90f487d

Browse files
committed
feat: move sync manager to LLC too
1 parent 339bf4f commit 90f487d

File tree

5 files changed

+53
-37
lines changed

5 files changed

+53
-37
lines changed

Diff for: package/src/components/Channel/Channel.tsx

+12-15
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,6 @@ import * as dbApi from '../../store/apis';
9494
import { ChannelUnreadState, FileTypes } from '../../types/types';
9595
import { addReactionToLocalState } from '../../utils/addReactionToLocalState';
9696
import { compressedImageURI } from '../../utils/compressImage';
97-
import { DBSyncManager } from '../../utils/DBSyncManager';
9897
import { patchMessageTextCommand } from '../../utils/patchMessageTextCommand';
9998
import { removeReactionFromLocalState } from '../../utils/removeReactionFromLocalState';
10099
import { removeReservedFields } from '../../utils/removeReservedFields';
@@ -1065,11 +1064,13 @@ const ChannelWithContext = (props: PropsWithChildren<ChannelPropsWithContext>) =
10651064
let connectionChangedSubscription: ReturnType<ChannelType['on']>;
10661065

10671066
if (enableOfflineSupport) {
1068-
connectionChangedSubscription = DBSyncManager.onSyncStatusChange((statusChanged) => {
1069-
if (statusChanged) {
1070-
connectionChangedHandler();
1071-
}
1072-
});
1067+
connectionChangedSubscription = client.offlineDb.syncManager.onSyncStatusChange(
1068+
(statusChanged) => {
1069+
if (statusChanged) {
1070+
connectionChangedHandler();
1071+
}
1072+
},
1073+
);
10731074
} else {
10741075
connectionChangedSubscription = client.on('connection.changed', (event) => {
10751076
if (event.online) {
@@ -1080,8 +1081,7 @@ const ChannelWithContext = (props: PropsWithChildren<ChannelPropsWithContext>) =
10801081
return () => {
10811082
connectionChangedSubscription.unsubscribe();
10821083
};
1083-
// eslint-disable-next-line react-hooks/exhaustive-deps
1084-
}, [enableOfflineSupport, shouldSyncChannel]);
1084+
}, [enableOfflineSupport, client, shouldSyncChannel]);
10851085

10861086
// In case the channel is disconnected which may happen when channel is deleted,
10871087
// underlying js client throws an error. Following function ensures that Channel component
@@ -1493,8 +1493,7 @@ const ChannelWithContext = (props: PropsWithChildren<ChannelPropsWithContext>) =
14931493

14941494
copyMessagesStateFromChannel(channel);
14951495

1496-
const sendReactionResponse = await DBSyncManager.queueTask({
1497-
client,
1496+
const sendReactionResponse = await client.offlineDb.syncManager.queueTask({
14981497
task: {
14991498
channelId: channel.id,
15001499
channelType: channel.type,
@@ -1523,7 +1522,7 @@ const ChannelWithContext = (props: PropsWithChildren<ChannelPropsWithContext>) =
15231522
}
15241523

15251524
if (message.status === MessageStatusTypes.FAILED) {
1526-
await DBSyncManager.dropPendingTasks({ messageId: message.id });
1525+
await client.offlineDb.syncManager.dropPendingTasks({ messageId: message.id });
15271526
await removeMessage(message);
15281527
} else {
15291528
const updatedMessage = {
@@ -1536,8 +1535,7 @@ const ChannelWithContext = (props: PropsWithChildren<ChannelPropsWithContext>) =
15361535

15371536
threadInstance?.upsertReplyLocally({ message: updatedMessage });
15381537

1539-
const data = await DBSyncManager.queueTask({
1540-
client,
1538+
const data = await client.offlineDb.syncManager.queueTask({
15411539
task: {
15421540
channelId: channel.id,
15431541
channelType: channel.type,
@@ -1577,8 +1575,7 @@ const ChannelWithContext = (props: PropsWithChildren<ChannelPropsWithContext>) =
15771575

15781576
copyMessagesStateFromChannel(channel);
15791577

1580-
await DBSyncManager.queueTask({
1581-
client,
1578+
await client.offlineDb.syncManager.queueTask({
15821579
task: {
15831580
channelId: channel.id,
15841581
channelType: channel.type,

Diff for: package/src/components/ChannelList/hooks/usePaginatedChannels.ts

+10-10
Original file line numberDiff line numberDiff line change
@@ -229,18 +229,18 @@ export const usePaginatedChannels = ({
229229
return true;
230230
};
231231

232-
let listener: ReturnType<typeof DBSyncManager.onSyncStatusChange>;
232+
let listener: ReturnType<typeof client.offlineDb.syncManager.onSyncStatusChange>;
233233
if (enableOfflineSupport) {
234234
// Any time DB is synced, we need to update the UI with local DB channels first,
235235
// and then call queryChannels to ensure any new channels are added to UI.
236-
listener = DBSyncManager.onSyncStatusChange(async (syncStatus) => {
237-
// if (syncStatus) {
238-
// const loadingChannelsSucceeded = await loadOfflineChannels();
239-
// if (loadingChannelsSucceeded) {
240-
// await reloadList();
241-
// setForceUpdate((u) => u + 1);
242-
// }
243-
// }
236+
listener = client.offlineDb.syncManager.onSyncStatusChange(async (syncStatus) => {
237+
if (syncStatus) {
238+
// const loadingChannelsSucceeded = await loadOfflineChannels();
239+
// if (loadingChannelsSucceeded) {
240+
await reloadList();
241+
// setForceUpdate((u) => u + 1);
242+
// }
243+
}
244244
});
245245
// On start, load the channels from local db.
246246
// loadOfflineChannels().then((success) => {
@@ -265,7 +265,7 @@ export const usePaginatedChannels = ({
265265

266266
return () => listener?.unsubscribe?.();
267267
// eslint-disable-next-line react-hooks/exhaustive-deps
268-
}, [filterStr, sortStr, channelManager]);
268+
}, [client, filterStr, sortStr, channelManager]);
269269

270270
return {
271271
channelListInitialized,

Diff for: package/src/components/Chat/Chat.tsx

+7-11
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import React, { PropsWithChildren, useEffect, useState } from 'react';
22
import { Image, Platform } from 'react-native';
33

4-
import type { Channel, StreamChat } from 'stream-chat';
4+
import type { Channel } from 'stream-chat';
55

66
import { useAppSettings } from './hooks/useAppSettings';
77
import { useCreateChatContext } from './hooks/useCreateChatContext';
@@ -27,7 +27,6 @@ import { NativeHandlers } from '../../native';
2727
import { OfflineDB } from '../../store/OfflineDB';
2828
import { SqliteClient } from '../../store/SqliteClient';
2929

30-
import { DBSyncManager } from '../../utils/DBSyncManager';
3130
import type { Streami18n } from '../../utils/i18n/Streami18n';
3231
import { version } from '../../version.json';
3332

@@ -215,18 +214,15 @@ const ChatWithContext = (props: PropsWithChildren<ChatProps>) => {
215214

216215
const initializeDatabase = () => {
217216
// TODO: Rethink this, it looks ugly
218-
console.log('TESTING2', client);
219-
const offlineDBInstance = new OfflineDB({ client });
220-
console.log(offlineDBInstance);
221-
client.setOfflineDBApi(offlineDBInstance);
217+
client.setOfflineDBApi(new OfflineDB({ client }));
222218
// This acts as a lock for some very rare occurrences of concurrency
223219
// issues we've encountered before with the QuickSqliteClient being
224220
// uninitialized before it's being invoked.
225221
setInitialisedDatabaseConfig({ initialised: false, userID });
226222
SqliteClient.initializeDatabase()
227223
.then(async () => {
228224
setInitialisedDatabaseConfig({ initialised: true, userID });
229-
await DBSyncManager.init(client as unknown as StreamChat);
225+
await client.offlineDb.syncManager.init();
230226
})
231227
.catch((error) => {
232228
console.log('Error Initializing DB:', error);
@@ -254,13 +250,13 @@ const ChatWithContext = (props: PropsWithChildren<ChatProps>) => {
254250
return () => {
255251
client.threads.unregisterSubscriptions();
256252
client.polls.unregisterSubscriptions();
253+
// In case something went wrong, make sure to also unsubscribe the listener
254+
// on unmount if it exists to prevent a memory leak.
255+
// FIXME: Should be wrapped in its own unregistration mechanism
256+
client.offlineDb.syncManager?.connectionChangedListener?.unsubscribe();
257257
};
258258
}, [client]);
259259

260-
// In case something went wrong, make sure to also unsubscribe the listener
261-
// on unmount if it exists to prevent a memory leak.
262-
useEffect(() => () => DBSyncManager.connectionChangedListener?.unsubscribe(), []);
263-
264260
const initialisedDatabase =
265261
initialisedDatabaseConfig.initialised && userID === initialisedDatabaseConfig.userID;
266262

Diff for: package/src/store/OfflineDB.ts

+21-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
1-
import { AbstractOfflineDB, GetChannelsForQueryType, GetChannelsType } from 'stream-chat';
1+
import { AbstractOfflineDB, GetLastSyncedAtType, UpsertUserSyncStatusType } from 'stream-chat';
2+
import type { GetChannelsForQueryType, GetChannelsType } from 'stream-chat';
23

34
import * as api from './apis';
5+
import { SqliteClient } from './SqliteClient';
46

57
export class OfflineDB extends AbstractOfflineDB {
68
upsertCidsForQuery = api.upsertCidsForQuery;
@@ -11,4 +13,22 @@ export class OfflineDB extends AbstractOfflineDB {
1113
// FIXME
1214
getChannelsForQuery = ({ userId, filters, sort }: GetChannelsForQueryType) =>
1315
api.getChannelsForFilterSort({ currentUserId: userId, filters, sort });
16+
17+
getAllChannelCids = api.getAllChannelIds;
18+
// FIXME
19+
getLastSyncedAt = ({ userId }: GetLastSyncedAtType) =>
20+
api.getLastSyncedAt({ currentUserId: userId });
21+
// FIXME
22+
upsertUserSyncStatus = ({ userId, lastSyncedAt }: UpsertUserSyncStatusType) =>
23+
api.upsertUserSyncStatus({ currentUserId: userId, lastSyncedAt });
24+
25+
addPendingTask = api.addPendingTask;
26+
27+
deletePendingTask = api.deletePendingTask;
28+
29+
getPendingTasks = api.getPendingTasks;
30+
31+
resetDB = SqliteClient.resetDB;
32+
33+
executeSqlBatch = SqliteClient.executeSqlBatch;
1434
}

Diff for: package/src/store/apis/index.ts

+3
Original file line numberDiff line numberDiff line change
@@ -22,3 +22,6 @@ export * from './upsertMembers';
2222
export * from './upsertMessages';
2323
export * from './upsertReads';
2424
export * from './updatePollMessage';
25+
export * from './addPendingTask';
26+
export * from './deletePendingTask';
27+
export * from './getPendingTasks';

0 commit comments

Comments
 (0)