generated from droyson/js-library-boilerplate
-
Notifications
You must be signed in to change notification settings - Fork 3
/
observable.ts
263 lines (241 loc) · 7.62 KB
/
observable.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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
import { deepEqual, isFunction, noop } from './helper'
import { Fetcher, Key, PublicConfiguration, SWRConfiguration, SWRObservable, SWRResponse, SWRWatcher, watchCallback } from './types'
const defaultConfiguration: PublicConfiguration<any, any> = {
compare: deepEqual,
dedupingInterval: 2000,
fallbackData: undefined,
onSuccess: noop,
onError: noop,
shouldRetryOnError: true,
errorRetryInterval: 5000,
errorRetryCount: 5,
refreshInterval: 0,
revalidateOnWatch: true,
revalidateOnFocus: true,
revalidateOnReconnect: true,
refreshWhenHidden: false,
refreshWhenOffline: false
}
const VISIBILITY_CHANGE = 'visibilitychange'
const FOCUS = 'focus'
const ONLINE = 'online'
const OFFLINE = 'offline'
export class Observable<Data = any, Error = any> implements SWRObservable<Data, Error> {
private _watchers: Watcher<Data, Error>[]
private _keyIsFunction: boolean
private _key: Key
private _fetcher: Fetcher<Data> | undefined
private _options: PublicConfiguration<Data, Error> = defaultConfiguration
private _data: Data | undefined = undefined
private _error: Error | undefined = undefined
private _isValidating = false
private _lastFetchTs = 0
private _errorRetryCounter = 0
private _online = true
private _timer: any
private _listeners: Record<string, EventListenerOrEventListenerObject> = {}
constructor(key: Key, fetcher?: Fetcher<Data>, options?: SWRConfiguration<Data, Error>) {
this._watchers = []
this._key = key
this._fetcher = fetcher
this._keyIsFunction = isFunction(key)
this._online = typeof navigator?.onLine === 'boolean' ? navigator.onLine : true
this._setOptions(options)
}
private get response (): SWRResponse<Data, Error> {
return {
data: this._data,
error: this._error,
isValidating: this._isValidating
}
}
private _setOptions (options?: SWRConfiguration<Data, Error>) {
this._options = {...defaultConfiguration, ...options}
if (typeof this._data === 'undefined') {
this._data = this._options.fallbackData
}
if (this._options.revalidateOnFocus) {
this._initFocus()
} else {
this._clearFocus()
}
if (this._options.revalidateOnReconnect) {
this._initReconnect()
} else {
this._clearReconnect()
}
}
setFetcher (fetcher: Fetcher<Data>, override = false): void {
if (!this._fetcher || override) {
this._fetcher = fetcher
}
}
watch (fn: watchCallback<Data, Error>): SWRWatcher {
const watcher = new Watcher(fn)
this._watchers.push(watcher)
if (this._options.revalidateOnWatch || this._data === undefined) {
this._callFetcher()
}
try {
fn(this.response)
} catch (err) {
// no-op
}
return watcher
}
mutate (options?: SWRConfiguration<Data, Error>): void {
if (typeof options !== 'undefined') {
this._setOptions(options)
}
this._callFetcher()
}
private _callWatchers():void {
const removedIndices: number[] = []
for (const index in this._watchers) {
const watcher = this._watchers[index]
if (typeof watcher._callback === 'function') {
try {
watcher._callback(this.response)
} catch (err) {
// no-op
}
} else {
removedIndices.push(parseInt(index))
}
}
for (const index of removedIndices) {
this._watchers.splice(index, 1)
}
}
private _callFetcher ():void {
if (!this._fetcher) {
return
}
const now = Date.now()
if ((now - this._lastFetchTs) < this._options.dedupingInterval) {
return
}
this._lastFetchTs = now
let key: any = this._key
if (this._keyIsFunction) {
try {
key = key()
} catch (err) {
key = null
}
}
if (typeof key === 'string') {
key = [key]
}
if (key !== null) {
try {
this._isValidating = true
Promise.resolve(this._fetcher.apply(this._fetcher, key)).then(data => {
const previousData = this._data
this._data = data as Data
this._error = undefined
this._isValidating = false
const onSuccess = this._options.onSuccess
onSuccess.apply(onSuccess, [data, key[0], this._options])
if (!this._options.compare(previousData, data)) {
this._callWatchers()
}
this._lastFetchTs = 0
this._errorRetryCounter = 0
if (this._options.refreshInterval > 0) {
this._timer = setTimeout(() => {
this._callFetcher()
}, this._options.refreshInterval)
}
}).catch((err) => this._errorHandler(err, key[0]))
} catch (err) {
this._errorHandler(err, key[0])
}
}
}
private _errorHandler (err: unknown, key: string) {
this._data = this._options.fallbackData
this._error = err as Error
this._isValidating = false
this._lastFetchTs = 0
const onError = this._options.onError
onError.apply(onError, [this._error, key, this._options])
this._callWatchers()
if (this._options.shouldRetryOnError && this._errorRetryCounter < this._options.errorRetryCount) {
if (this._options.onErrorRetry) {
const revalidateOptions = {
retryCount: this._errorRetryCounter++
}
this._options.onErrorRetry(this._error, key, this._options, this._callFetcher.bind(this), revalidateOptions)
} else {
// Exponential back-off
const timeout = ~~((Math.random() + 0.5) * (1 << Math.min(this._errorRetryCounter, 8))) * this._options.errorRetryInterval
setTimeout(() => {
this._errorRetryCounter++
this._callFetcher()
}, timeout)
}
}
}
private _isVisible (): boolean {
return document?.visibilityState !== 'hidden'
}
private _visibilityListener () {
if (this._isVisible()) {
this._callFetcher()
} else if (this._timer && !this._options.refreshWhenHidden) {
clearTimeout(this._timer)
}
}
private _onlineListener () {
this._online = true
this._callFetcher()
}
private _offlineListener () {
this._online = false
if (this._timer && !this._options.refreshWhenOffline) {
clearTimeout(this._timer)
}
}
private _initFocus () {
this._listeners.focus = this._visibilityListener.bind(this)
if (typeof document?.addEventListener === 'function') {
document.addEventListener(VISIBILITY_CHANGE, this._listeners.focus)
}
if (typeof window?.addEventListener === 'function') {
window.addEventListener(FOCUS, this._listeners.focus)
}
}
private _initReconnect () {
this._listeners.online = this._onlineListener.bind(this)
this._listeners.offline = this._offlineListener.bind(this)
if (typeof window?.addEventListener === 'function') {
window.addEventListener(ONLINE, this._listeners.online)
window.addEventListener(OFFLINE, this._listeners.offline)
}
}
private _clearFocus () {
if (typeof document?.removeEventListener === 'function') {
document.removeEventListener(VISIBILITY_CHANGE, this._listeners.focus)
}
if (typeof window?.removeEventListener === 'function') {
document.removeEventListener(FOCUS, this._listeners.focus)
}
delete this._listeners.focus
}
private _clearReconnect () {
if (typeof window?.removeEventListener === 'function') {
window.removeEventListener(ONLINE, this._listeners.online)
window.removeEventListener(OFFLINE, this._listeners.offline)
}
}
}
class Watcher<Data, Error> implements SWRWatcher {
_callback: watchCallback<Data, Error> | null;
constructor(fn: watchCallback<Data, Error>) {
this._callback = fn
}
unwatch ():void {
this._callback = null
}
}