unjs/unstorage

Multiple Driver Fallback Support

dalezak opened this issue · 2 comments

Describe the feature

Is it possible to define multiple drivers with fallback logic?

For example use IndexDB if supported, else fallback to use LocalStorage.

This is something that LocalForage supports, which is great to have this "use best option" functionality.

localForage.config({
  driver: [
    this.unstorage.INDEXEDDB,
    this.unstorage.WEBSQL,
    this.unstorage.LOCALSTORAGE
  ]
});

Is this currently possible with unstorage? If not could this be implemented with a custom driver?

Additional information

  • Would you be willing to help implement this feature?

One idea is a simple try-catch, try using indexedDbDriver, if it fails then fallback to localStorageDriver.

try {
  this.unstorage = createStorage({
    driver: indexedDbDriver({
      storeName: "app"
    })
  });
}
catch (error) {
  this.unstorage = createStorage({
    driver: localStorageDriver()
  });
}

Will this work? Is there a better option?

I suggest implementing a few common policies like read-through/write-through etc.
see: https://www.prisma.io/dataguide/managing-databases/introduction-database-caching
I've recently implemented a TieredStorage driver in my own project, it's under tests and I'll create a PR when it's ready.