-
Notifications
You must be signed in to change notification settings - Fork 4
/
SaveQueue.js
39 lines (34 loc) · 1.06 KB
/
SaveQueue.js
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
import { catchAsync } from 'source/common/error'
const NULL_FUNC = () => {}
const createSaveQueue = ({
onError,
doSave,
beforeSave = NULL_FUNC,
afterSave = NULL_FUNC
}) => {
let dataQueue = []
let isSaving = false
let savingState = {} // for doSave to expose save state, do not leak unnecessary info
const setSavingState = (nextSavingState) => { savingState = nextSavingState }
const saveAsync = async () => {
beforeSave()
const savingDataQueue = dataQueue
dataQueue = []
isSaving = true
const { error } = await catchAsync(doSave, savingDataQueue, setSavingState)
isSaving = false
savingState = {}
if (error) throw error
afterSave()
}
return {
clear: () => { dataQueue = [] },
add: (data) => dataQueue.push(data),
save: () => { !isSaving && dataQueue.length && saveAsync().catch(onError) },
filter: (filterFunc) => { dataQueue = dataQueue.filter(filterFunc) },
getLength: () => dataQueue.length,
getIsSaving: () => isSaving,
getSavingState: () => savingState
}
}
export { createSaveQueue }