bitburner-src/src/db.tsx
catloversg 8553bcb8fc
MISC: Support compression of save data (#1162)
* Use Compression Streams API instead of jszip or other libraries.
* Remove usage of base64 in the new binary format.
* Do not convert binary data to string and back. The type of save data is SaveData, it's either string (old base64 format) or Uint8Array (new binary format).
* Proper support for interacting with electron-related code. Electron-related code assumes that save data is in the base64 format.
* Proper support for other tools (DevMenu, pretty-save.js). Full support for DevMenu will be added in a follow-up PR. Check the comments in src\DevMenu\ui\SaveFileDev.tsx for details.
2024-03-27 21:08:09 -07:00

76 lines
2.2 KiB
TypeScript

import { SaveData } from "./types";
function getDB(): Promise<IDBObjectStore> {
return new Promise((resolve, reject) => {
if (!window.indexedDB) {
reject("Indexed DB does not exists");
}
/**
* DB is called bitburnerSave
* Object store is called savestring
* key for the Object store is called save
* Version `1` is important
*/
const indexedDbRequest: IDBOpenDBRequest = window.indexedDB.open("bitburnerSave", 1);
// This is called when there's no db to begin with. It's important, don't remove it.
indexedDbRequest.onupgradeneeded = function (this: IDBRequest<IDBDatabase>) {
const db = this.result;
db.createObjectStore("savestring");
};
indexedDbRequest.onerror = function (this: IDBRequest<IDBDatabase>, ev: Event) {
reject(`Failed to get IDB ${ev}`);
};
indexedDbRequest.onsuccess = function (this: IDBRequest<IDBDatabase>) {
const db = this.result;
if (!db) {
reject("database loading result was undefined");
return;
}
resolve(db.transaction(["savestring"], "readwrite").objectStore("savestring"));
};
});
}
export function load(): Promise<SaveData> {
return new Promise((resolve, reject) => {
getDB()
.then((db) => {
return new Promise<SaveData>((resolve, reject) => {
const request: IDBRequest<SaveData> = db.get("save");
request.onerror = function (this: IDBRequest<SaveData>, ev: Event) {
reject("Error in Database request to get save data: " + ev);
};
request.onsuccess = function (this: IDBRequest<SaveData>) {
resolve(this.result);
};
}).then((saveData) => resolve(saveData));
})
.catch((r) => reject(r));
});
}
export function save(saveData: SaveData): Promise<void> {
return getDB().then((db) => {
return new Promise<void>((resolve, reject) => {
// We'll save to IndexedDB
const request = db.put(saveData, "save");
request.onerror = function (e) {
reject("Error saving game to IndexedDB: " + e);
};
request.onsuccess = () => resolve();
});
});
}
export function deleteGame(): Promise<void> {
return getDB().then((db) => {
db.delete("save");
});
}