setup.ts 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import type { Pinia } from 'pinia';
  2. import type { App } from 'vue';
  3. import { createPinia } from 'pinia';
  4. import SecureLS from 'secure-ls';
  5. let pinia: Pinia;
  6. type SecureLSStorage = {
  7. get(key: string): any;
  8. set(key: string, value: unknown): void;
  9. };
  10. type SecureLSCtor = new (config?: {
  11. encodingType?: string;
  12. encryptionSecret?: string;
  13. isCompression?: boolean;
  14. metaKey?: string;
  15. }) => SecureLSStorage;
  16. const secureLSModule = SecureLS as unknown as {
  17. default?: SecureLSCtor;
  18. SecureLS?: SecureLSCtor;
  19. };
  20. const SecureLSConstructor =
  21. secureLSModule.default ??
  22. secureLSModule.SecureLS ??
  23. (SecureLS as unknown as SecureLSCtor);
  24. export interface InitStoreOptions {
  25. /**
  26. * @zh_CN 应用名,由于 @vben/stores 是公用的,后续可能有多个app,为了防止多个app缓存冲突,可在这里配置应用名,应用名将被用于持久化的前缀
  27. */
  28. namespace: string;
  29. }
  30. /**
  31. * @zh_CN 初始化pinia
  32. */
  33. export async function initStores(app: App, options: InitStoreOptions) {
  34. const { createPersistedState } = await import('pinia-plugin-persistedstate');
  35. pinia = createPinia();
  36. const { namespace } = options;
  37. const ls = new SecureLSConstructor({
  38. encodingType: 'aes',
  39. encryptionSecret: import.meta.env.VITE_APP_STORE_SECURE_KEY,
  40. isCompression: true,
  41. metaKey: `${namespace}-secure-meta`,
  42. });
  43. pinia.use(
  44. createPersistedState({
  45. // key $appName-$store.id
  46. key: (storeKey) => `${namespace}-${storeKey}`,
  47. storage: import.meta.env.DEV
  48. ? localStorage
  49. : {
  50. getItem(key) {
  51. return ls.get(key);
  52. },
  53. setItem(key, value) {
  54. ls.set(key, value);
  55. },
  56. },
  57. }),
  58. );
  59. app.use(pinia);
  60. return pinia;
  61. }
  62. export function resetAllStores() {
  63. if (!pinia) {
  64. console.error('Pinia is not installed');
  65. return;
  66. }
  67. const allStores = (pinia as any)._s;
  68. for (const [_key, store] of allStores) {
  69. store.$reset();
  70. }
  71. }