diff --git a/server/src/plugins/crdt/collaboration-server.ts b/server/src/plugins/crdt/collaboration-server.ts index 2ad92028a..51eba30f3 100644 --- a/server/src/plugins/crdt/collaboration-server.ts +++ b/server/src/plugins/crdt/collaboration-server.ts @@ -5,6 +5,8 @@ import { isDeployed } from '@app/config/env'; import { getRedisExtension } from '@app/plugins/crdt/redis'; import { isNotNull } from '@app/functions/guards'; import { getApiExtension } from '@app/plugins/crdt/api/extension'; +import { getDocument } from '@app/plugins/crdt/get-document'; +import { applyUpdate } from 'yjs'; const log = getLogger('collaboration'); @@ -35,5 +37,30 @@ export const collaborationServer = Server.configure({ } }, + onLoadDocument: async ({ context, document }) => { + if (!isConnectionContext(context)) { + log.error({ msg: 'Tried to load document without context' }); + throw new Error('Invalid context'); + } + + if (!document.isEmpty('content')) { + log.info({ msg: 'Document already loaded' }); + + return document; + } + + const { behandlingId, dokumentId, req } = context; + + const res = await getDocument(req, behandlingId, dokumentId); + + log.info({ msg: 'Fetched document', data: { behandlingId, dokumentId } }); + + const state = Buffer.from(res.data, 'base64'); + + applyUpdate(document, state); + + return document; + }, + extensions: isDeployed ? [getRedisExtension(), getApiExtension()].filter(isNotNull) : [getApiExtension()], });