| 102 | } |
| 103 | |
| 104 | export function rxdbCollectionOptions(config: RxDBCollectionConfig<any, any>) { |
| 105 | type Row = Record<string, unknown> |
| 106 | type Key = string // because RxDB primary keys must be strings |
| 107 | |
| 108 | const { ...restConfig } = config |
| 109 | const rxCollection = config.rxCollection |
| 110 | |
| 111 | // "getKey" |
| 112 | const primaryPath = rxCollection.schema.primaryPath |
| 113 | function getKey(item: Record<string, unknown>): string { |
| 114 | const key: string = item[primaryPath] as string |
| 115 | return key |
| 116 | } |
| 117 | |
| 118 | /** |
| 119 | * "sync" |
| 120 | * Notice that this describes the Sync between the local RxDB collection |
| 121 | * and the in-memory tanstack-db collection. |
| 122 | * It is not about sync between a client and a server! |
| 123 | */ |
| 124 | type SyncParams = Parameters<SyncConfig<Row, string>[`sync`]>[0] |
| 125 | const sync: SyncConfig<Row, Key> = { |
| 126 | sync: (params: SyncParams) => { |
| 127 | const { begin, write, commit, markReady } = params |
| 128 | |
| 129 | let ready = false |
| 130 | async function initialFetch() { |
| 131 | /** |
| 132 | * RxDB stores a last-write-time |
| 133 | * which can be used to "sort" document writes, |
| 134 | * so for initial sync we iterate over that. |
| 135 | */ |
| 136 | let cursor: RxDocumentData<Row> | undefined = undefined |
| 137 | const syncBatchSize = config.syncBatchSize ? config.syncBatchSize : 1000 |
| 138 | begin() |
| 139 | |
| 140 | while (!ready) { |
| 141 | let query: FilledMangoQuery<Row> |
| 142 | if (cursor) { |
| 143 | query = { |
| 144 | selector: { |
| 145 | $or: [ |
| 146 | { '_meta.lwt': { $gt: cursor._meta.lwt } }, |
| 147 | { |
| 148 | '_meta.lwt': cursor._meta.lwt, |
| 149 | [primaryPath]: { |
| 150 | $gt: getKey(cursor), |
| 151 | }, |
| 152 | }, |
| 153 | ], |
| 154 | _deleted: false, |
| 155 | }, |
| 156 | sort: [{ '_meta.lwt': `asc` }, { [primaryPath]: `asc` }], |
| 157 | limit: syncBatchSize, |
| 158 | skip: 0, |
| 159 | } |
| 160 | } else { |
| 161 | query = { |