Skip to content

Instantly share code, notes, and snippets.

@jfrancos
Last active January 14, 2022 04:13
Show Gist options
  • Save jfrancos/bb11ec6cada6a8fc0addc6d688f66ede to your computer and use it in GitHub Desktop.
Save jfrancos/bb11ec6cada6a8fc0addc6d688f66ede to your computer and use it in GitHub Desktop.
Turn an RxDB `bulkInsert` into an exported indexeddb.json file using Node.js
import 'fake-indexeddb/auto';
import { readFile, writeFile } from 'fs/promises';
import { exportToJsonString } from 'indexeddb-export-import';
import { getDatabase } from './Database';
const inFile = 'bulkInsertableData.json';
const outFile = 'indexeddb.json';
const collectionName = 'collection';
const prepIndexedDB = async () => {
const buffer = await readFile(inFile);
const object = JSON.parse(buffer.toString());
const db = await getDatabase();
await db[collectionName].bulkInsert(object);
await db.remove();
const request = indexedDB.open(`${db.name}.db`);
request.onsuccess = () => {
exportToJsonString(request.result, (err: Event, idbAsString: string) => {
if (err) {
console.log({ err });
}
writeFile(outFile, idbAsString);
});
};
};
@jfrancos
Copy link
Author

jfrancos commented Jan 11, 2022

Where getDatabase is as per the examples e.g.

const getDatabase = () => {
  dbPromise = dbPromise || _create();
  return dbPromise;
};

And I use it like

ts-node --transpile-only --skip-project docs-to-indexeddb.ts

Then to restore:

const name = "name"
const storage = ...
const filename = "indexeddb.json"

const createDatabaseAndCollection = async () => {
  const db = await createRxDatabase({ name, storage });
  await db.addCollections({ ... });
  return db;
};

const _create = async () => {
  const exists = (await window.indexedDB.databases())
    .map((db) => db.name)
    .includes(`${name}.db`);
  let db = await createDatabaseAndCollection();
  if (!exists) {
    await db.destroy();
    await restoreIndexeddb();
    db = await createDatabaseAndCollection();
  }
  return db;
};

const restoreIndexeddb = async () => {
  const response = await fetch(filename);
  const data = await response.text();
  const request = window.indexedDB.open(`${name}.db`);
  request.onsuccess = async () => {
    clearDatabase(request.result, (err: Event) => {
      if (err) {
        console.log({ err });
        return;
      }
      importFromJsonString(request.result, data, async (err: Event) => {
        if (err) {
          console.log({ err });
          return;
        }
        request.result.close();
        resolve(null);
      });
    });
  };
};

const getDatabase = () => {
  dbPromise = dbPromise || _create();
  return dbPromise;
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment