How to migrate existing Dexie database to new Dexi

2019-08-21 04:24发布

I have web application which uses Dexie wrapper for indexedDB, for some reason i need to rename existing Database with no glitch, i couldn't find renaming on Dexie documentation.

1条回答
放荡不羁爱自由
2楼-- · 2019-08-21 05:22

There's no support to rename a database is neither Dexie or native indexedDB. But you can clone a database using the following piece of code (not tested):

function cloneDatabase (sourceName, destinationName) {
  //
  // Open source database
  //
  const origDb = new Dexie(sourceName);
  return origDb.open().then(()=> {
    // Create the destination database
    const destDb = new Dexie(destinationName);

    //
    // Clone Schema
    //
    const schema = origDb.tables.reduce((result,table)=>{
      result[table.name] = [table.schema.primKey]
        .concat(table.schema.indexes)
        .map(indexSpec => indexSpec.src);
      return result;
    }, {});
    destDb.version(origDb.verno).stores(schema);

    //
    // Clone Data
    //
    return origDb.tables.reduce(

      (prev, table) => prev
        .then(() => table.toArray())
        .then(rows => destDb.table(table.name).bulkAdd(rows)),

      Promise.resolve()

    ).then(()=>{
      //
      // Finally close the databases
      //
      origDb.close();
      destDb.close();
    });
  });
}
查看更多
登录 后发表回答