refactor(storage): use unstorage

This commit is contained in:
molvqingtai 2023-11-16 23:54:04 +08:00
parent 9d3a1d81cd
commit 3067485417
4 changed files with 31 additions and 11 deletions

View file

@ -4,7 +4,7 @@ import { Remesh } from 'remesh'
import { RemeshRoot } from 'remesh-react'
import { RemeshLogger } from 'remesh-logger'
import App from './App'
import StorageImpl from '@/impl/Storage'
import { StorageIndexDBImpl } from '@/impl/Storage'
import '@/assets/styles/tailwind.css'
export default defineContentScript({
@ -12,7 +12,7 @@ export default defineContentScript({
matches: ['*://*.example.com/*', '*://*.google.com/*', '*://*.v2ex.com/*'],
async main(ctx) {
const store = Remesh.store({
externs: [StorageImpl],
externs: [StorageIndexDBImpl],
inspectors: [RemeshLogger()]
})

View file

@ -9,7 +9,7 @@ const MessageListDomain = Remesh.domain({
name: 'MessageListDomain',
impl: (domain) => {
const storage = domain.getExtern(Storage)
const storageKey = `${storage.name}.MESSAGE_LIST`
const storageKey = `MESSAGE_LIST`
const MessageListModule = ListModule<Message>(domain, {
name: 'MessageListModule',

View file

@ -1,9 +1,12 @@
import { Remesh } from 'remesh'
export type StorageValue = null | string | number | boolean | object
export interface Storage {
name: string
get: <T>(key: string) => Promise<T | undefined>
set: <T>(key: string, value: T) => Promise<void>
get: <T extends StorageValue>(key: string) => Promise<T | null>
set: <T extends StorageValue>(key: string, value: T) => Promise<void>
clear: () => Promise<void>
}
const StorageExtern = Remesh.extern<Storage>({
@ -14,6 +17,9 @@ const StorageExtern = Remesh.extern<Storage>({
},
set: async () => {
throw new Error('"set" not implemented')
},
clear: async () => {
throw new Error('"clear" not implemented')
}
}
})

View file

@ -1,11 +1,25 @@
import { get, set } from 'idb-keyval'
import indexedDbDriver from 'unstorage/drivers/indexedb'
import StorageExtern from '@/domain/externs/Storage'
import { STORAGE_NAME } from '@/constants'
const StorageImpl = StorageExtern.impl({
name: STORAGE_NAME,
get,
set
const browserLocalStorage = createStorage({
driver: webExtensionDriver({ storageArea: 'local' })
})
export default StorageImpl
const indexDBStorage = createStorage({
driver: indexedDbDriver({ base: `${STORAGE_NAME}:` })
})
export const StorageIndexDBImpl = StorageExtern.impl({
name: STORAGE_NAME,
get: indexDBStorage.getItem,
set: indexDBStorage.setItem,
clear: indexDBStorage.clear
})
export const StorageBrowserLocalImpl = StorageExtern.impl({
name: STORAGE_NAME,
get: browserLocalStorage.getItem,
set: browserLocalStorage.setItem,
clear: browserLocalStorage.clear
})