2022-11-23 23:12:25 +00:00
|
|
|
import type { Driver } from 'unstorage'
|
2023-02-12 11:56:29 +00:00
|
|
|
import memory from 'unstorage/drivers/memory'
|
2022-11-23 23:12:25 +00: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
|
|
|
|
|
2023-07-02 17:11:13 +00:00
|
|
|
return driver.hasItem(key, {})
|
2022-11-23 23:12:25 +00:00
|
|
|
},
|
|
|
|
async setItem(key: string, value: any) {
|
|
|
|
await Promise.all([
|
|
|
|
memoryDriver.setItem(key, value),
|
2023-07-02 17:11:13 +00:00
|
|
|
driver.setItem?.(key, value, {}),
|
2022-11-23 23:12:25 +00:00
|
|
|
])
|
|
|
|
},
|
|
|
|
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
|
|
|
|
},
|
|
|
|
}
|
|
|
|
})
|