This repository has been archived by the owner on Mar 27, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathplugin.ts
46 lines (39 loc) · 1.8 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
import { defineStore, DefineStoreOptions, PiniaPluginContext, StateTree, Store, StoreDefinition, _GettersTree } from 'pinia';
import { createStorage, Storage } from 'unstorage';
import { PluginOptions, StoreOptions } from './type';
const configureStore = (store: Store, storage: Storage, filter?: Array<string>) => {
storage.getItem(store.$id).then((state) => {
Object.assign(store, state);
});
const _filter = (filter) ?? Object.keys(store.$state);
store.$subscribe(() => storage.setItem(store.$id,
JSON.stringify(Object.fromEntries(
Object.entries(store.$state).filter(([key]) => (_filter.indexOf(key) ?? 0) > -1)
))
));
storage.setItem(store.$id,
JSON.stringify(Object.fromEntries(
Object.entries(store.$state).filter(([key]) => (_filter.indexOf(key) ?? 0) > -1)
))
);
};
const unstorageOptionsBag: Record<string, StoreOptions> = {};
// eslint-disable-next-line @typescript-eslint/ban-types
export const defineUnstore = <Id extends string, S extends StateTree = {}, G extends _GettersTree<S> = {}, A = {}>(id: Id, options: Omit<DefineStoreOptions<Id, S, G, A>, 'id'>, unstorageOptions: StoreOptions): StoreDefinition<Id, S, G, A> => {
const store = defineStore(id, options);
unstorageOptionsBag[id] = unstorageOptions;
return store;
};
export const createUnstoragePlugin = ({ driver }: PluginOptions = {}) => {
return({ options, store }: PiniaPluginContext) => {
if(options.unstorage) {
configureStore(store, createStorage({ driver: options.unstorage.driver }), options.unstorage.filter);
}
else if(unstorageOptionsBag[store.$id]) {
configureStore(store, createStorage({ driver: unstorageOptionsBag[store.$id].driver }), unstorageOptionsBag[store.$id].filter );
}
else if(driver) {
configureStore(store, createStorage({ driver }));
}
};
};