I have recently used yjs, so my question may seem silly, but I have been looking for a long time and have not found the right way
I am using GitHub - MaxNoetzold/y-mongodb-provider: Mongodb database adapter for Yjs for persistence storage. This is the code for persistence, taken from the README:
setPersistence({
bindState: async (docName: string, ydoc: Y.Doc) => {
// Here you listen to granular document updates and store them in the database
// You don't have to do this, but it ensures that you don't lose content when the server crashes
// See https://github.com/yjs/yjs#Document-Updates for documentation on how to encode
// document updates
// official default code from: https://github.com/yjs/y-websocket/blob/37887badc1f00326855a29fc6b9197745866c3aa/bin/utils.js#L36
const persistedYdoc = await mdb.getYDoc(docName);
const newUpdates = Y.encodeStateAsUpdate(ydoc);
mdb.storeUpdate(docName, newUpdates);
Y.applyUpdate(ydoc, Y.encodeStateAsUpdate(persistedYdoc));
ydoc.on('update', async (update) => {
mdb.storeUpdate(docName, update);
});
},
writeState: async (docName, ydoc) => {
// This is called when all connections to the document are closed.
// In the future, this method might also be called in intervals or after a certain number of updates.
return new Promise((resolve) => {
// When the returned Promise resolves, the document will be destroyed.
// So make sure that the document really has been written to the database.
resolve(undefined);
});
},
});
Now, I have implemented an interface for replicating documents. Here is the code:
async duplicate(sourceFileId: string, destFileId: string): Promise<void> {
const mdb = this.getMongodbPersistence();
let sourceDocName = this.generateDocNameByFileId(sourceFileId);
let destDocName = this.generateDocNameByFileId(destFileId);
const sourceYdoc = await mdb.getYDoc(sourceDocName);
mdb.storeUpdate(destDocName, Y.encodeStateAsUpdate(sourceYdoc));
const destYdoc = await mdb.getYDoc(destDocName);
}
From my observation, it seems that the content of destYdoc has been replicated. However, when I send the doc to the client through setPersistence
, the content is incomplete.