2022-11-24 08:12:25 +09:00
|
|
|
import type { Driver } from 'unstorage'
|
2023-02-12 20:56:29 +09:00
|
|
|
import memory from 'unstorage/drivers/memory'
|
2022-11-24 08:12:25 +09:00
|
|
|
import { defineDriver } from 'unstorage'
|
|
|
|
|
|
|
|
export interface CacheDriverOptions {
|
|
|
|
driver: Driver
|
|
|
|
}
|
|
|
|
|
|
|
|
export default defineDriver((driver: Driver = memory()) => {
|
|
|
|
const memoryDriver = memory()
|
|
|
|
return {
|
|
|
|
...driver,
|
|
|
|
async hasItem(key: string) {
|
|
|
|
if (await memoryDriver.hasItem(key))
|
|
|
|
return true
|
|
|
|
|
|
|
|
return driver.hasItem(key)
|
|
|
|
},
|
|
|
|
async setItem(key: string, value: any) {
|
|
|
|
await Promise.all([
|
|
|
|
memoryDriver.setItem(key, value),
|
|
|
|
driver.setItem?.(key, value),
|
|
|
|
])
|
|
|
|
},
|
|
|
|
async getItem(key: string) {
|
|
|
|
let value = await memoryDriver.getItem(key)
|
|
|
|
|
|
|
|
if (value !== null)
|
|
|
|
return value
|
|
|
|
|
|
|
|
value = await driver.getItem(key)
|
|
|
|
memoryDriver.setItem(key, value)
|
|
|
|
|
|
|
|
return value
|
|
|
|
},
|
|
|
|
}
|
|
|
|
})
|