-
-
Notifications
You must be signed in to change notification settings - Fork 392
/
FileImport.ts
86 lines (74 loc) · 2.65 KB
/
FileImport.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import { ImmutablePayloadCollection } from '../Collection/Payload/ImmutablePayloadCollection'
import { ConflictDelta } from './Conflict'
import { FullyFormedPayloadInterface, isDecryptedPayload, PayloadEmitSource } from '../../Abstract/Payload'
import { HistoryMap } from '../History'
import { extendSyncDelta, SourcelessSyncDeltaEmit, SyncDeltaEmit } from './Abstract/DeltaEmit'
import { DeltaInterface } from './Abstract/DeltaInterface'
import { SyncResolvedPayload } from './Utilities/SyncResolvedPayload'
import { getIncrementedDirtyIndex } from '../DirtyCounter/DirtyCounter'
export class DeltaFileImport implements DeltaInterface {
constructor(
readonly baseCollection: ImmutablePayloadCollection,
private readonly applyPayloads: FullyFormedPayloadInterface[],
protected readonly historyMap: HistoryMap,
) {}
public result(): SyncDeltaEmit {
const result: SyncDeltaEmit = {
emits: [],
ignored: [],
source: PayloadEmitSource.FileImport,
}
for (const payload of this.applyPayloads) {
const resolved = this.resolvePayload(payload, result)
extendSyncDelta(result, resolved)
}
return result
}
private resolvePayload(payload: FullyFormedPayloadInterface, currentResults: SyncDeltaEmit): SourcelessSyncDeltaEmit {
/**
* Check to see if we've already processed a payload for this id.
* If so, that would be the latest value, and not what's in the base collection.
*/
/*
* Find the most recently created conflict if available, as that
* would contain the most recent value.
*/
let current = currentResults.emits.find((candidate) => {
return isDecryptedPayload(candidate) && candidate.content.conflict_of === payload.uuid
})
/**
* If no latest conflict, find by uuid directly.
*/
if (!current) {
current = currentResults.emits.find((candidate) => {
return candidate.uuid === payload.uuid
})
}
/**
* If not found in current results, use the base value.
*/
if (!current) {
const base = this.baseCollection.find(payload.uuid)
if (base && isDecryptedPayload(base)) {
current = base as SyncResolvedPayload
}
}
/**
* If the current doesn't exist, we're creating a new item from payload.
*/
if (!current) {
return {
emits: [
payload.copyAsSyncResolved({
dirty: true,
dirtyIndex: getIncrementedDirtyIndex(),
lastSyncEnd: new Date(0),
}),
],
ignored: [],
}
}
const delta = new ConflictDelta(this.baseCollection, current, payload, this.historyMap)
return delta.result()
}
}