-
Notifications
You must be signed in to change notification settings - Fork 31
/
entry.ts
72 lines (65 loc) · 1.95 KB
/
entry.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
import { Channel } from './channel'
import { MemoizedSignal } from './signal'
import { EntryAPI, EntryFieldInfo, EntrySys, Metadata, TaskAPI } from './types'
import { ExhaustiveEntryFieldAPI } from './types/field.types'
const taskMethods: Array<keyof TaskAPI> = [
'getTask',
'getTasks',
'createTask',
'updateTask',
'deleteTask',
]
export default function createEntry(
channel: Channel,
entryData: any,
fieldInfo: EntryFieldInfo[],
createEntryField: (info: EntryFieldInfo) => ExhaustiveEntryFieldAPI,
): EntryAPI {
let sys = entryData.sys
const sysChanged = new MemoizedSignal<[EntrySys]>(sys)
let metadata = entryData.metadata
const metadataChanged = new MemoizedSignal<[Metadata | undefined]>(metadata)
channel.addHandler('sysChanged', (newSys: Metadata) => {
sys = newSys
sysChanged.dispatch(sys)
})
channel.addHandler('metadataChanged', (newMetadata: Metadata) => {
metadata = newMetadata
metadataChanged.dispatch(metadata)
})
const taskApi = {} as TaskAPI
taskMethods.forEach((methodName) => {
taskApi[methodName] = function (...args: any[]) {
return channel.call('callEntryMethod', methodName, args)
} as any
})
return {
getSys() {
return sys
},
publish(options?: { skipUiValidation?: boolean }) {
return channel.call<void>('callEntryMethod', 'publish', [options])
},
unpublish() {
return channel.call<void>('callEntryMethod', 'unpublish')
},
save() {
return channel.call<void>('callEntryMethod', 'save')
},
onSysChanged(handler: (sys: EntrySys) => void) {
return sysChanged.attach(handler)
},
fields: fieldInfo.reduce((acc: any, info: EntryFieldInfo) => {
acc[info.id] = createEntryField(info)
return acc
}, {}),
...(metadata ? { metadata } : {}),
getMetadata() {
return metadata
},
onMetadataChanged(handler: VoidFunction) {
return metadataChanged.attach(handler)
},
...taskApi,
}
}