giantdb
Version:
Large object database in native JavaScript, with encryption support
77 lines (76 loc) • 2.32 kB
JavaScript
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Change = void 0;
const writable_wrapper_1 = __importDefault(require("writable-wrapper"));
/**
* An object representing a change on an item, still to be committed.
*/
class Change extends writable_wrapper_1.default {
id;
_committer;
_destroyer;
_changeFinished;
/**
* Constructs a new Change.
*
* @param id The ID of the new item.
* @param writeStream The output stream to write to.
* @param committer The function used for committing.
* @param destroyer The function used for destruction.
*/
constructor(id, writeStream, committer, destroyer) {
super(writeStream);
this.id = id;
this._changeFinished = false;
this._committer = committer;
this._destroyer = destroyer;
this.on('error', () => {
if (this._destroyer != null) {
void this._destroyer();
this._committer = undefined;
this._destroyer = undefined;
}
});
this.on('finish', () => {
this._changeFinished = true;
});
}
/**
* Commit this change. This ends the output and makes the item available.
*
* @returns A Promise that resolves to an Item, or rejects on error.
*/
async commit() {
if (this._committer == null) {
throw new Error('invalid state');
}
const committer = this._committer;
const destroyer = this._destroyer;
this._committer = undefined;
this._destroyer = undefined;
try {
await this._finalizeBeforeCommit();
}
catch (err) {
if (destroyer != null) {
await destroyer();
}
throw err;
}
return await committer();
}
async _finalizeBeforeCommit() {
if (this._changeFinished) {
return;
}
await new Promise((resolve, reject) => {
this.once('error', reject);
this.once('finish', resolve);
this.end();
});
}
}
exports.Change = Change;