diff --git a/src/app/_helpers/index.ts b/src/app/_helpers/index.ts index 46ddbe2..82fdb87 100644 --- a/src/app/_helpers/index.ts +++ b/src/app/_helpers/index.ts @@ -8,3 +8,4 @@ export * from '@app/_helpers/http-getter'; export * from '@app/_helpers/mock-backend'; export * from '@app/_helpers/read-csv'; export * from '@app/_helpers/schema-validation'; +export * from '@app/_helpers/sync'; diff --git a/src/app/_helpers/sync.ts b/src/app/_helpers/sync.ts new file mode 100644 index 0000000..9a0840b --- /dev/null +++ b/src/app/_helpers/sync.ts @@ -0,0 +1,31 @@ +import { ArgPair, Syncable } from 'cic-client-meta'; +import * as Automerge from 'automerge'; + +export function updateSyncable( + changes: Array, + changesDescription: string, + syncable: Syncable +): any { + syncable.m = Automerge.change(syncable.m, changesDescription, (m) => { + changes.forEach((c) => { + const path = c.k.split('.'); + let target = m['data']; + while (path.length > 1) { + const part = path.shift(); + target = target[part]; + } + try { + target[path[0]] = c.v; + } catch (e) { + if ( + !e.message.includes( + 'Cannot assign an object that already belongs to an Automerge document.' + ) + ) { + throw new Error(e); + } + } + }); + m['timestamp'] = Math.floor(Date.now() / 1000); + }); +} diff --git a/src/app/_services/user.service.ts b/src/app/_services/user.service.ts index 1844e78..240b6c8 100644 --- a/src/app/_services/user.service.ts +++ b/src/app/_services/user.service.ts @@ -12,7 +12,7 @@ import { MutableKeyStore, PGPSigner, Signer } from '@app/_pgp'; import { RegistryService } from '@app/_services/registry.service'; import { CICRegistry } from '@cicnet/cic-client'; import { AuthService } from '@app/_services/auth.service'; -import { personValidation, vcardValidation } from '@app/_helpers'; +import { personValidation, updateSyncable, vcardValidation } from '@app/_helpers'; import { add0x } from '@src/assets/js/ethtx/dist/hex'; const vCard = require('vcard-parser'); @@ -108,7 +108,7 @@ export class UserService { for (const prop of Object.keys(accountInfo)) { update.push(new ArgPair(prop, accountInfo[prop])); } - syncableAccount.update(update, 'client-branch'); + updateSyncable(update, 'client-branch', syncableAccount); await personValidation(syncableAccount.m.data); await this.updateMeta(syncableAccount, accountKey, this.headers); },