feat(core): await sync doc (#4247)

This commit is contained in:
Alex Yang
2023-09-06 20:54:39 -07:00
committed by GitHub
parent 8656530049
commit 1d1fb6ca31
3 changed files with 82 additions and 87 deletions
+37
View File
@@ -1,3 +1,6 @@
import type { Doc as YDoc } from 'yjs';
import { applyUpdate, encodeStateAsUpdate } from 'yjs';
import type { DocState } from './types';
export interface DatasourceDocAdapter {
@@ -26,6 +29,40 @@ export interface DatasourceDocAdapter {
): () => void;
}
export async function syncDocFromDataSource(
rootDoc: YDoc,
datasource: DatasourceDocAdapter
) {
const downloadDocStateRecursively = async (doc: YDoc) => {
const docState = await datasource.queryDocState(doc.guid);
if (docState) {
applyUpdate(doc, docState.missing, 'sync-doc-from-datasource');
}
await Promise.all(
[...doc.subdocs].map(async subdoc => {
await downloadDocStateRecursively(subdoc);
})
);
};
await downloadDocStateRecursively(rootDoc);
}
export async function syncDataSourceFromDoc(
rootDoc: YDoc,
datasource: DatasourceDocAdapter
) {
const uploadDocStateRecursively = async (doc: YDoc) => {
await datasource.sendDocUpdate(doc.guid, encodeStateAsUpdate(doc));
await Promise.all(
[...doc.subdocs].map(async subdoc => {
await uploadDocStateRecursively(subdoc);
})
);
};
await uploadDocStateRecursively(rootDoc);
}
/**
* query the datasource from source, and save the latest update to target
*