-
Notifications
You must be signed in to change notification settings - Fork 405
/
operationEvents.ts
206 lines (190 loc) · 5.92 KB
/
operationEvents.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
/* eslint-disable max-nested-callbacks */
import {type SanityClient} from '@sanity/client'
import {type Schema} from '@sanity/types'
import {asyncScheduler, defer, EMPTY, merge, type Observable, of, Subject, timer} from 'rxjs'
import {
catchError,
concatMap,
filter,
groupBy,
last,
map,
mergeMap,
mergeMapTo,
share,
switchMap,
take,
tap,
throttleTime,
} from 'rxjs/operators'
import {type HistoryStore} from '../../history'
import {type IdPair} from '../types'
import {memoize} from '../utils/createMemoizer'
import {consistencyStatus} from './consistencyStatus'
import {operationArgs} from './operationArgs'
import {type OperationArgs, type OperationsAPI} from './operations'
import {commit} from './operations/commit'
import {del} from './operations/delete'
import {discardChanges} from './operations/discardChanges'
import {duplicate} from './operations/duplicate'
import {patch} from './operations/patch'
import {publish} from './operations/publish'
import {restore} from './operations/restore'
import {unpublish} from './operations/unpublish'
import {del as serverDel} from './serverOperations/delete'
import {patch as serverPatch} from './serverOperations/patch'
import {publish as serverPublish} from './serverOperations/publish'
import {unpublish as serverUnpublish} from './serverOperations/unpublish'
interface ExecuteArgs {
operationName: keyof OperationsAPI
idPair: IdPair
typeName: string
extraArgs: any[]
}
function maybeObservable(v: void | Observable<any>) {
return typeof v === 'undefined' ? of(null) : v
}
const operationImpls = {
del: del,
delete: del,
publish,
patch,
commit,
discardChanges,
unpublish,
duplicate,
restore,
} as const
//as we add server operations one by one, we can add them here
const serverOperationImpls = {
...operationImpls,
del: serverDel,
delete: serverDel,
patch: serverPatch,
publish: serverPublish,
unpublish: serverUnpublish,
}
const execute = (
operationName: keyof typeof operationImpls,
operationArguments: OperationArgs,
extraArgs: any[],
serverActionsEnabled?: boolean,
): Observable<any> => {
const operation = serverActionsEnabled
? serverOperationImpls[operationName]
: operationImpls[operationName]
return defer(() =>
merge(of(null), maybeObservable(operation.execute(operationArguments, ...extraArgs))),
).pipe(last())
}
const operationCalls$ = new Subject<ExecuteArgs>()
/** @internal */
export function emitOperation(
operationName: keyof OperationsAPI,
idPair: IdPair,
typeName: string,
extraArgs: any[],
): void {
operationCalls$.next({operationName, idPair, typeName, extraArgs})
}
// These are the operations that cannot be performed while the document is in an inconsistent state
const REQUIRES_CONSISTENCY = ['publish', 'unpublish', 'discardChanges', 'delete']
/**
* @hidden
* @beta */
export interface OperationError {
type: 'error'
/** @internal */
op: keyof OperationsAPI
id: string
error: Error
}
/**
* @hidden
* @beta */
export interface OperationSuccess {
type: 'success'
/** @internal */
op: keyof OperationsAPI
id: string
}
interface IntermediarySuccess {
type: 'success'
args: ExecuteArgs
}
interface IntermediaryError {
type: 'error'
args: ExecuteArgs
error: any
}
/** @internal */
export const operationEvents = memoize(
(ctx: {
client: SanityClient
historyStore: HistoryStore
schema: Schema
serverActionsEnabled?: boolean
}) => {
const result$: Observable<IntermediarySuccess | IntermediaryError> = operationCalls$.pipe(
groupBy((op) => op.idPair.publishedId),
mergeMap((groups$) =>
groups$.pipe(
// although it might look like a bug, dropping pending async operations here is actually a feature
// E.g. if the user types `publish` which is async and then starts patching (sync) then the publish
// should be cancelled
switchMap((args) =>
operationArgs(ctx, args.idPair, args.typeName).pipe(
take(1),
switchMap((operationArguments) => {
const requiresConsistency = REQUIRES_CONSISTENCY.includes(args.operationName)
if (requiresConsistency) {
operationArguments.published.commit()
operationArguments.draft.commit()
}
const isConsistent$ = consistencyStatus(
ctx.client,
args.idPair,
args.typeName,
).pipe(filter(Boolean))
const ready$ = requiresConsistency ? isConsistent$.pipe(take(1)) : of(true)
return ready$.pipe(
switchMap(() =>
execute(
args.operationName,
operationArguments,
args.extraArgs,
ctx.serverActionsEnabled,
),
),
)
}),
map((): IntermediarySuccess => ({type: 'success', args})),
catchError(
(err): Observable<IntermediaryError> => of({type: 'error', args, error: err}),
),
),
),
),
),
share(),
)
// this enables autocommit after patch operations
const AUTOCOMMIT_INTERVAL = 1000
const autoCommit$ = result$.pipe(
filter((result) => result.type === 'success' && result.args.operationName === 'patch'),
throttleTime(AUTOCOMMIT_INTERVAL, asyncScheduler, {leading: true, trailing: true}),
concatMap((result) =>
(window as any).SLOW ? timer(10000).pipe(map(() => result)) : of(result),
),
tap((result) => {
emitOperation('commit', result.args.idPair, result.args.typeName, [])
}),
)
return merge(result$, autoCommit$.pipe(mergeMapTo(EMPTY)))
},
(ctx) => {
const config = ctx.client.config()
// we only want one of these per dataset+projectid
return `${config.dataset ?? ''}-${config.projectId ?? ''}`
},
)