[feat] opfs storage
This commit is contained in:
77
src/ts/storage/autoStorage.ts
Normal file
77
src/ts/storage/autoStorage.ts
Normal file
@@ -0,0 +1,77 @@
|
||||
import localforage from "localforage"
|
||||
import { isNodeServer } from "./globalApi"
|
||||
import { NodeStorage } from "./nodeStorage"
|
||||
import { OpfsStorage } from "./opfsStorage"
|
||||
import { alertConfirm, alertStore } from "../alert"
|
||||
|
||||
export class AutoStorage{
|
||||
|
||||
realStorage:LocalForage|NodeStorage|OpfsStorage
|
||||
|
||||
async setItem(key:string, value:Uint8Array) {
|
||||
await this.Init()
|
||||
return await this.realStorage.setItem(key, value)
|
||||
}
|
||||
async getItem(key:string):Promise<Buffer> {
|
||||
await this.Init()
|
||||
return await this.realStorage.getItem(key)
|
||||
|
||||
}
|
||||
async keys():Promise<string[]>{
|
||||
await this.Init()
|
||||
return await this.realStorage.keys()
|
||||
|
||||
}
|
||||
async removeItem(key:string){
|
||||
await this.Init()
|
||||
return await this.realStorage.removeItem(key)
|
||||
}
|
||||
|
||||
private async Init(){
|
||||
if(!this.realStorage){
|
||||
if(isNodeServer){
|
||||
console.log("using node storage")
|
||||
this.realStorage = new NodeStorage()
|
||||
return
|
||||
}
|
||||
else if(window.navigator?.storage?.getDirectory && localStorage.getItem('flag_opfs')){
|
||||
console.log("using opfs storage")
|
||||
|
||||
const forage = localforage.createInstance({
|
||||
name: "risuai"
|
||||
})
|
||||
|
||||
const i = await forage.getItem("database/database.bin")
|
||||
|
||||
if((!i) || (await forage.getItem("migrated"))){
|
||||
this.realStorage = new OpfsStorage()
|
||||
return
|
||||
}
|
||||
else if(!(await forage.getItem("denied_opfs"))){
|
||||
console.log("migrating")
|
||||
const keys = await forage.keys()
|
||||
let i = 0;
|
||||
const opfs = new OpfsStorage()
|
||||
for(const key of keys){
|
||||
console.log(i)
|
||||
alertStore.set({
|
||||
type: "none",
|
||||
msg: `Migrating your data...(${i}/${keys.length})`
|
||||
})
|
||||
await opfs.setItem(key,await forage.getItem(key))
|
||||
i += 1
|
||||
}
|
||||
this.realStorage = opfs
|
||||
await forage.setItem("migrated", true)
|
||||
return
|
||||
}
|
||||
}
|
||||
console.log("using forage storage")
|
||||
this.realStorage = localforage.createInstance({
|
||||
name: "risuai"
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
listItem = this.keys
|
||||
}
|
||||
Reference in New Issue
Block a user