-
Notifications
You must be signed in to change notification settings - Fork 9
/
plugin.ts
214 lines (198 loc) · 5.16 KB
/
plugin.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
import * as shvl from 'shvl'
import type {
PiniaPlugin,
PiniaPluginContext,
StateTree,
SubscriptionCallback,
} from 'pinia'
import type { PluginOptions, CommonOptions } from './type'
function defaultTo<T>(a: T | null | undefined, b: T) {
return a != null ? a : b
}
function getOption<T, K extends keyof T>(
fallback: T[K],
key: K,
options1: T,
options2: T,
) {
return defaultTo(
defaultTo(options1[key], options2[key]),
fallback,
) as Required<T>[K]
}
export function createPersistedStatePlugin<S extends StateTree = StateTree>(
options?: PluginOptions<S>,
): PiniaPlugin {
const pluginOptions = options || ({} as PluginOptions<StateTree>)
function plugin(context: PiniaPluginContext) {
// normalize
const options = (function () {
try {
return context.options.persistedState || {}
} catch {
return {}
}
})()
if (getOption(true, 'persist', options, pluginOptions) === false) return
const key = getOption(context.store.$id, 'key', options, {})
const overwrite = getOption(false, 'overwrite', options, pluginOptions)
const storage = getOption(
(function () {
try {
return window.localStorage
} catch {
return {
getItem: function () {},
setItem: function () {},
removeItem: function () {},
}
}
})(),
'storage',
options,
pluginOptions,
)
const filter = getOption(
function () {
return true
},
'filter',
options,
pluginOptions,
)
const serialize = getOption(
JSON.stringify,
'serialize',
options,
pluginOptions,
)
const deserialize = getOption(
JSON.parse,
'deserialize',
options,
pluginOptions,
)
const migrate = getOption(
function <T>(_: T) {
return _
},
'migrate',
options,
{},
)
const merge = getOption(
function (state, savedState) {
return savedState
},
'merge',
options,
{},
)
if (
process.env.NODE_ENV === 'development' ||
process.env.NODE_ENV === 'test'
) {
if (options.assertStorage === void 0) {
options.assertStorage = function (
storage: Required<CommonOptions<S>>['storage'],
) {
const uniqueKey = '@@'
const result = storage.setItem(uniqueKey, '1')
const removeItem = function () {
storage.removeItem(uniqueKey)
}
if (result instanceof Promise) {
result.then(removeItem)
} else {
removeItem()
}
}
}
options.assertStorage(storage)
}
// hydrate
// initialize custom properties
let resolveIsReady: Function
const isReadyPromise = new Promise<void>(function (resolve) {
resolveIsReady = resolve
})
let pendingCount = 0
context.store.$persistedState = {
isReady: function () {
return isReadyPromise
},
pending: false,
}
function patchOrOverwrite(state: any) {
;(options.beforeHydrate || function () {})(context.store.$state)
const merged = merge(context.store.$state, state)
if (overwrite) {
context.store.$state = merged
} else {
context.store.$patch(merged)
}
resolveIsReady()
}
function parse(value: any) {
if (value != null) {
const state = deserialize(value)
const migrateState = migrate(state)
if (migrateState instanceof Promise) {
migrateState.then(patchOrOverwrite)
} else {
patchOrOverwrite(migrateState)
}
} else {
resolveIsReady()
}
}
try {
const value = storage.getItem(key)
if (value instanceof Promise) {
value.then(parse)
} else {
parse(value)
}
} catch (error) {
if (
process.env.NODE_ENV === 'development' ||
process.env.NODE_ENV === 'test'
)
console.warn(error)
resolveIsReady!()
}
// persist
const callback: SubscriptionCallback<S> = function (mutation, state) {
if (filter(mutation, state) === false) return
if (Array.isArray(options.includePaths)) {
state = options.includePaths.reduce(function (partialState, path) {
return shvl.set(
partialState,
path,
shvl.get(state as Record<string, unknown>, path),
)
}, {} as any)
}
if (Array.isArray(options.excludePaths)) {
state = deserialize(serialize(state))
options.excludePaths.forEach(function (path) {
return shvl.set(state, path, void 0)
}, {})
}
const value = serialize(state)
const result = storage.setItem(key, value)
if (result instanceof Promise) {
++pendingCount
context.store.$persistedState.pending = pendingCount !== 0
result
.catch(function () {})
.finally(function () {
--pendingCount
context.store.$persistedState.pending = pendingCount !== 0
})
}
}
context.store.$subscribe(callback)
}
return plugin
}