@alwatr/nitrobase-reference
Version:
Nitrobase is a blazingly fast, lightweight database built on JSON. It stores data entirely in memory for lightning-quick access, while also providing a JSON file backup for persistence. You can easily serve your data over the web using our high-performanc
970 lines (964 loc) • 30.4 kB
JavaScript
/* @alwatr/nitrobase-reference v7.8.0 */
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/main.ts
var main_exports = {};
__export(main_exports, {
CollectionReference: () => CollectionReference,
DocumentReference: () => DocumentReference
});
module.exports = __toCommonJS(main_exports);
// src/collection-reference.ts
var import_nanolib2 = require("@alwatr/nanolib");
var import_nitrobase_helper = require("@alwatr/nitrobase-helper");
var import_nitrobase_types = require("@alwatr/nitrobase-types");
// src/logger.ts
var import_nanolib = require("@alwatr/nanolib");
__dev_mode__: import_nanolib.packageTracer.add("@alwatr/nitrobase-reference", "7.8.0");
var logger = /* @__PURE__ */ (0, import_nanolib.createLogger)("@alwatr/nitrobase-reference");
// src/collection-reference.ts
__dev_mode__: logger.logFileModule?.("collection-reference");
var _CollectionReference = class _CollectionReference {
/**
* Collection reference have methods to get, set, update and save the Alwatr Nitrobase Collection.
* This class is dummy in saving and loading the collection from file.
* It's the responsibility of the Alwatr Nitrobase to save and load the collection.
*
* @param context__ Collection's context filled from the Alwatr Nitrobase (parent).
* @param updatedCallback__ updated callback to invoke when the collection is updated from the Alwatr Nitrobase (parent).
* @template TItem - Items data type.
* @example
* ```typescript
* const collectionRef = alwatrStore.col('blog/posts');
* ```
*/
constructor(context__, updatedCallback__, debugDomain) {
this.context__ = context__;
this.updatedCallback__ = updatedCallback__;
/**
* Indicates whether the collection has unsaved changes.
*/
this.hasUnprocessedChanges_ = false;
/**
* Indicates whether the collection data is frozen and cannot be saved.
*/
this._freeze = false;
this.updateDelayed_ = false;
this.id = (0, import_nitrobase_helper.getStoreId)(this.context__.meta);
this.path = (0, import_nitrobase_helper.getStorePath)(this.context__.meta);
debugDomain ?? (debugDomain = this.id.slice(0, 20));
this.logger__ = (0, import_nanolib2.createLogger)(`col:${debugDomain}`);
this.logger__.logMethodArgs?.("new", { id: this.id });
this.validateContext__();
}
/**
* Creates new CollectionReference instance from stat.
*
* @param stat the collection stat.
* @param initialData the collection data.
* @param updatedCallback the callback to invoke when the collection changed.
* @template TItem The collection item data type.
* @returns A new collection reference class.
*/
static newRefFromData(stat, updatedCallback, debugDomain) {
logger.logMethodArgs?.("col.newRefFromData", stat);
const now = Date.now();
const initialContext = {
ok: true,
meta: {
...stat,
rev: 1,
updated: now,
created: now,
lastAutoId: 0,
type: import_nitrobase_types.StoreFileType.Collection,
extension: import_nitrobase_types.StoreFileExtension.Json,
fv: _CollectionReference.fileFormatVersion,
extra: {}
},
data: {}
};
return new _CollectionReference(initialContext, updatedCallback, debugDomain);
}
/**
* Creates new CollectionReference instance from CollectionContext.
*
* @param context the collection context.
* @param updatedCallback the callback to invoke when the collection changed.
* @template TItem The collection item data type.
* @returns A new collection reference class.
*/
static newRefFromContext(context, updatedCallback, debugDomain) {
logger.logMethodArgs?.("col.newRefFromContext", context.meta);
return new _CollectionReference(context, updatedCallback, debugDomain);
}
/**
* Validates the collection context and try to migrate it to the latest version.
*/
validateContext__() {
this.logger__.logMethod?.("validateContext__");
if (this.context__.ok !== true) {
this.logger__.accident?.("validateContext__", "store_not_ok");
throw new Error("store_not_ok", { cause: { context: this.context__ } });
}
if (this.context__.meta === void 0) {
this.logger__.accident?.("validateContext__", "store_meta_undefined");
throw new Error("store_meta_undefined", { cause: { context: this.context__ } });
}
if (this.context__.meta.type !== import_nitrobase_types.StoreFileType.Collection) {
this.logger__.accident?.("validateContext__", "collection_type_invalid", this.context__.meta);
throw new Error("collection_type_invalid", { cause: this.context__.meta });
}
if (this.context__.meta.fv !== _CollectionReference.fileFormatVersion) {
this.logger__.incident?.("validateContext__", "store_file_version_incompatible", {
old: this.context__.meta.fv,
new: _CollectionReference.fileFormatVersion
});
this.migrateContext__();
}
}
/**
* Migrate the collection context to the latest.
*/
migrateContext__() {
var _a;
if (this.context__.meta.fv === _CollectionReference.fileFormatVersion) return;
this.logger__.logMethod?.("migrateContext__");
if (this.context__.meta.fv > _CollectionReference.fileFormatVersion) {
this.logger__.accident("migrateContext__", "store_version_incompatible", this.context__.meta);
throw new Error("store_version_incompatible", { cause: this.context__.meta });
}
if (this.context__.meta.fv === 1) {
this.context__.meta.fv = 2;
}
if (this.context__.meta.fv === 2) {
if (this.context__.meta.schemaVer === void 0 || this.context__.meta.schemaVer === 0) {
this.context__.meta.schemaVer = 1;
}
delete this.context__.meta["ver"];
(_a = this.context__.meta).extra ?? (_a.extra = {});
this.context__.meta.fv = 3;
}
this.updated__();
}
/**
* Get nitrobase schema version
*
* @returns nitrobase schema version
*/
get schemaVer() {
return this.context__.meta.schemaVer ?? 1;
}
/**
* Set nitrobase schema version for migrate
*/
set schemaVer(ver) {
this.logger__.logMethodArgs?.("set schemaVer", { old: this.context__.meta.schemaVer, new: ver });
this.context__.meta.schemaVer = ver;
this.updated__();
}
/**
* Gets the freeze status of the collection data.
*
* @returns `true` if the collection data is frozen, `false` otherwise.
*
* @example
* ```typescript
* const isFrozen = collectionRef.freeze;
* console.log(isFrozen); // Output: false
* ```
*/
get freeze() {
return this._freeze;
}
/**
* Sets the freeze status of the collection data.
*
* @param value - The freeze status to set.
*
* @example
* ```typescript
* collectionRef.freeze = true;
* console.log(collectionRef.freeze); // Output: true
* ```
*/
set freeze(value) {
this.logger__.logMethodArgs?.("freeze changed", { value });
this._freeze = value;
}
/**
* Checks if an item exists in the collection.
*
* @param itemId - The ID of the item.
* @returns `true` if the item with the given ID exists in the collection, `false` otherwise.
*
* @example
* ```typescript
* const doesExist = collectionRef.hasItem('item1');
*
* if (doesExist) {
* collectionRef.addItem('item1', { key: 'value' });
* }
* ```
*/
hasItem(itemId) {
const exists = Object.hasOwn(this.context__.data, itemId);
this.logger__.logMethodFull?.("hasItem", itemId, exists);
return exists;
}
/**
* Retrieves the metadata of the nitrobase file.
*
* @returns The metadata of the nitrobase file.
*
* @example
* ```typescript
* const metadata = collectionRef.getStoreMeta();
* ```
*/
getStoreMeta() {
this.logger__.logMethod?.("getStoreMeta");
return this.context__.meta;
}
/**
* Retrieves an item from the collection. If the item does not exist, an error is thrown.
*
* @param itemId - The ID of the item.
* @returns The item with the given ID.
*/
item__(itemId) {
const item = this.context__.data[itemId];
if (item === void 0) {
this.logger__.accident("item__", "collection_item_not_found", { itemId });
throw new Error("collection_item_not_found", { cause: { itemId } });
}
return item;
}
/**
* Retrieves an item's metadata from the collection. If the item does not exist, an error is thrown.
*
* @param itemId - The ID of the item.
* @returns The metadata of the item with the given ID.
* @example
* ```typescript
* const itemMeta = collectionRef.getItemMeta('item1');
* ```
*/
getItemMeta(itemId) {
const meta = this.item__(itemId).meta;
this.logger__.logMethodFull?.("getItemMeta", itemId, meta);
return meta;
}
/**
* Retrieves an item's data from the collection. If the item does not exist, an error is thrown.
*
* @param itemId - The ID of the item.
* @returns The data of the item with the given ID.
*
* @example
* ```typescript
* const itemData = collectionRef.getItemData('item1');
* ```
*/
getItemData(itemId) {
this.logger__.logMethodArgs?.("getItemData", itemId);
return this.item__(itemId).data;
}
/**
* Direct access to an item.
* If the item does not exist, `undefined` is returned.
* **USE WITH CAUTION!**
*
* @param itemId - The ID of the item.
* @returns The data of the item with the given ID or `undefined` if the item does not exist.
*
* @example
* ```typescript
* collectionRef.getItemContext_('item1')?.data.name = 'test2';
* ```
*/
getItemContext_(itemId) {
this.logger__.logMethodArgs?.("getItemContext_", itemId);
return this.context__.data[itemId];
}
/**
* Add a new item to the collection.
* If an item with the given ID already exists, an error is thrown.
*
* @param itemId - The ID of the item to create.
* @param data - The initial data of the item.
*
* @example
* ```typescript
* collectionRef.addItem('item1', { key: 'value' });
* ```
*/
addItem(itemId, data) {
this.logger__.logMethodArgs?.("addItem", { itemId, data });
if (this.hasItem(itemId)) {
this.logger__.accident("addItem", "collection_item_exist", { itemId });
throw new Error("collection_item_exist", { cause: { itemId } });
}
const now = Date.now();
this.context__.data[itemId] = {
meta: {
id: itemId,
// other prop calc in updateMeta__
rev: 0,
created: now,
updated: now
},
data
};
this.updated__(itemId);
}
/**
* Appends the given data to the collection with auto increment ID.
*
* @param data - The data to append.
* @returns The ID of the appended item.
*
* @example
* ```typescript
* const newId = collectionRef.appendItem({ key: 'value' });
* ```
*/
appendItem(data) {
this.logger__.logMethodArgs?.("appendItem", data);
const id = this.nextAutoIncrementId__();
this.addItem(id, data);
return id;
}
/**
* Removes an item from the collection.
*
* @param itemId - The ID of the item to delete.
*
* @example
* ```typescript
* collectionRef.removeItem('item1');
* collectionRef.hasItem('item1'); // Output: false
* ```
*/
removeItem(itemId) {
this.logger__.logMethodArgs?.("removeItem", itemId);
delete this.context__.data[itemId];
this.updated__();
}
/**
* Sets an item's data in the collection. Replaces the item's data with the given data.
*
* @param itemId - The ID of the item to set.
* @param data - The data to set for the item.
*
* @example
* ```typescript
* collectionRef.replaceItemData('item1', { a: 1, b: 2, c: 3 });
* ```
*/
replaceItemData(itemId, data) {
this.logger__.logMethodArgs?.("replaceItemData", { itemId, data });
this.item__(itemId).data = data;
this.updated__(itemId);
}
/**
* Updates an item in the collection by merging a partial update into the item's data.
*
* @param itemId - The ID of the item to update.
* @param data - The part of data to merge into the item's data.
*
* @example
* ```typescript
* collectionRef.mergeItemData(itemId, partialUpdate);
* ```
*/
mergeItemData(itemId, data) {
this.logger__.logMethodArgs?.("mergeItemData", { itemId, data });
Object.assign(this.item__(itemId).data, data);
this.updated__(itemId);
}
/**
* Requests the Alwatr Nitrobase to save the collection.
* Saving may take some time in Alwatr Nitrobase due to the use of throttling.
*
* @example
* ```typescript
* collectionRef.save();
* ```
*/
save(itemId) {
this.logger__.logMethod?.("save");
this.updated__(itemId, false);
}
/**
* Requests the Alwatr Nitrobase to save the collection immediately.
*
* @example
* ```typescript
* collectionRef.saveImmediate();
* ```
*/
saveImmediate(itemId) {
this.logger__.logMethod?.("saveImmediate");
this.updated__(itemId, true);
}
/**
* Retrieves the IDs of all items in the collection in array.
* Impact performance if the collection is large, use `ids()` instead.
*
* @returns Array of IDs of all items in the collection.
* @example
* ```typescript
* const ids = collectionRef.keys();
* ```
*/
keys() {
this.logger__.logMethod?.("keys");
return Object.keys(this.context__.data);
}
/**
* Retrieves all items in the collection in array.
* Impact performance if the collection is large, use `items()` instead.
*
* @returns Array of all items in the collection.
* @example
* ```typescript
* const items = collectionRef.values();
* console.log('meta: %o', items[0].meta);
* console.log('data: %o', items[0].data);
* ```
*/
values() {
this.logger__.logMethod?.("values");
return Object.values(this.context__.data);
}
/**
* Retrieves the IDs of all items in the collection.
* Use this method instead of `keys()` if the collection is large.
* This method is a generator and can be used in `for...of` loops.
* @returns Generator of IDs of all items in the collection.
* @example
* ```typescript
* for (const id of collectionRef.ids()) {
* const doc = collectionRef.get(id);
* }
* ```
*/
*ids() {
this.logger__.logMethod?.("ids");
for (const id in this.context__.data) {
yield id;
}
}
/**
* Retrieves all items in the collection.
* Use this method instead of `values()` if the collection is large.
* This method is a generator and can be used in `for...of` loops.
* @returns Generator of all items in the collection.
* @example
* ```typescript
* for (const item of collectionRef.items()) {
* console.log(item.data);
* }
*/
*items() {
this.logger__.logMethod?.("items");
for (const id in this.context__.data) {
yield this.context__.data[id];
}
}
/**
* Retrieves the full context of the collection.
*
* @returns The full context of the collection.
*
* @example
* ```typescript
* const context = collectionRef.getFullContext_();
* ```
*/
getFullContext_() {
this.logger__.logMethod?.("getFullContext_");
return this.context__;
}
/**
* Update the document metadata and invoke the updated callback.
* This method is throttled to prevent multiple updates in a short time.
*
* @param itemId - The ID of the item to update.
*/
async updated__(itemId = null, immediate = false) {
this.logger__.logMethodArgs?.("updated__", { id: itemId, immediate, delayed: this.updateDelayed_ });
this.hasUnprocessedChanges_ = true;
if (itemId !== null) this.refreshMeta_(itemId);
if (immediate === false && this.updateDelayed_ === true) return;
this.updateDelayed_ = true;
if (immediate === true || this.context__.meta.changeDebounce === void 0) {
await import_nanolib2.delay.immediate();
} else {
await import_nanolib2.delay.by(this.context__.meta.changeDebounce);
}
if (this.updateDelayed_ !== true) return;
this.updateDelayed_ = false;
if (itemId === null) this.refreshMeta_(itemId);
if (this._freeze === true) return;
this.updatedCallback__(this);
}
/**
* Refresh/recalculate the collection's metadata timestamp and revision.
*
* @param itemId - The ID of the item to update.
*/
refreshMeta_(itemId) {
this.logger__.logMethodArgs?.("refreshMeta_", { id: itemId });
const now = Date.now();
this.context__.meta.rev++;
this.context__.meta.updated = now;
if (itemId !== null) {
const itemMeta = this.item__(itemId).meta;
itemMeta.rev++;
itemMeta.updated = now;
}
}
/**
* Generates the next auto increment ID.
*
* @returns The next auto increment ID.
* @example
* ```typescript
* const nextId = this.nextAutoIncrementId_();
* ```
*/
nextAutoIncrementId__() {
this.logger__.logMethod?.("nextAutoIncrementId__");
const meta = this.context__.meta;
do {
meta.lastAutoId++;
} while (meta.lastAutoId in this.context__.data);
return meta.lastAutoId;
}
/**
* Retrieves the collection's extra metadata.
*
* @returns The collection's extra metadata.
*
* @example
* ```typescript
* const colExtraMeta = collectionRef.getExtraMeta();
* ```
*/
getExtraMeta() {
this.logger__.logMethod?.("getExtraMeta");
return this.context__.meta.extra;
}
/**
* Sets/replace the collection's extra metadata.
*
* @param extraMeta The new collection's extra metadata.
*
* @example
* ```typescript
* collectionRef.replaceExtraMeta({ a: 1, b: 2, c: 3 });
* ```
*/
replaceExtraMeta(extraMeta) {
this.logger__.logMethodArgs?.("replaceExtraMeta", extraMeta);
this.context__.meta.extra = extraMeta;
this.updated__();
}
/**
* Updates collection's extra metadata by merging a partial update.
*
* @param extraMeta The part of extra metadata to merge into the collection's extra metadata.
*
* @example
* ```typescript
* collectionRef.mergeExtraMeta({ c: 4 });
* ```
*/
mergeExtraMeta(extraMeta) {
this.logger__.logMethodArgs?.("mergeExtraMeta", extraMeta);
Object.assign(this.context__.meta.extra, extraMeta);
this.updated__();
}
};
/**
* Alwatr nitrobase engine version string.
*/
_CollectionReference.version = "7.8.0";
/**
* Alwatr nitrobase engine file format version number.
*/
_CollectionReference.fileFormatVersion = 3;
var CollectionReference = _CollectionReference;
// src/document-reference.ts
var import_nanolib3 = require("@alwatr/nanolib");
var import_nitrobase_helper2 = require("@alwatr/nitrobase-helper");
var import_nitrobase_types2 = require("@alwatr/nitrobase-types");
__dev_mode__: logger.logFileModule?.("document-reference");
var _DocumentReference = class _DocumentReference {
/**
* Create a new document reference.
* Document reference have methods to get, set, update and save the AlwatrNitrobase Document.
*
* @param context__ Document's context filled from the Alwatr Nitrobase (parent).
* @param updatedCallback__ updated callback to invoke when the document is updated from the Alwatr Nitrobase (parent).
* @template TDoc The document data type.
*/
constructor(context__, updatedCallback__, debugDomain) {
this.context__ = context__;
this.updatedCallback__ = updatedCallback__;
/**
* Indicates whether the document has unsaved changes.
*/
this.hasUnprocessedChanges_ = false;
/**
* Indicates whether the document data is frozen and cannot be saved.
*/
this._freeze = false;
this.updateDelayed_ = false;
this.id = (0, import_nitrobase_helper2.getStoreId)(this.context__.meta);
this.path = (0, import_nitrobase_helper2.getStorePath)(this.context__.meta);
debugDomain ?? (debugDomain = this.id.slice(0, 20));
this.logger__ = (0, import_nanolib3.createLogger)(`doc:${debugDomain}`);
this.logger__.logMethodArgs?.("new", { path: this.path });
this.validateContext__();
}
/**
* Creates new DocumentReference instance from stat and initial data.
*
* @param statId the document stat.
* @param data the document data.
* @param updatedCallback the callback to invoke when the document changed.
* @template TDoc The document data type.
* @returns A new document reference class.
*/
static newRefFromData(statId, data, updatedCallback, debugDomain) {
logger.logMethodArgs?.("doc.newRefFromData", statId);
const now = Date.now();
const initialContext = {
ok: true,
meta: {
...statId,
rev: 1,
updated: now,
created: now,
type: import_nitrobase_types2.StoreFileType.Document,
extension: import_nitrobase_types2.StoreFileExtension.Json,
fv: _DocumentReference.fileFormatVersion,
extra: {}
},
data
};
return new _DocumentReference(initialContext, updatedCallback, debugDomain);
}
/**
* Creates new DocumentReference instance from DocumentContext.
*
* @param context the document context.
* @param updatedCallback the callback to invoke when the document changed.
* @template TDoc The document data type.
* @returns A new document reference class.
*/
static newRefFromContext(context, updatedCallback, debugDomain) {
logger.logMethodArgs?.("doc.newRefFromContext", context.meta);
return new _DocumentReference(context, updatedCallback, debugDomain);
}
/**
* Validates the document context and try to migrate it to the latest version.
*/
validateContext__() {
this.logger__.logMethod?.("validateContext__");
if (this.context__.ok !== true) {
this.logger__.accident?.("validateContext__", "store_not_ok");
throw new Error("store_not_ok", { cause: { context: this.context__ } });
}
if (this.context__.meta === void 0) {
this.logger__.accident?.("validateContext__", "store_meta_undefined");
throw new Error("store_meta_undefined", { cause: { context: this.context__ } });
}
if (this.context__.meta.type !== import_nitrobase_types2.StoreFileType.Document) {
this.logger__.accident?.("validateContext__", "document_type_invalid", this.context__.meta);
throw new Error("document_type_invalid", { cause: this.context__.meta });
}
if (this.context__.meta.fv !== _DocumentReference.fileFormatVersion) {
this.logger__.incident?.("validateContext__", "store_file_version_incompatible", {
old: this.context__.meta.fv,
new: _DocumentReference.fileFormatVersion
});
this.migrateContext__();
}
}
/**
* Migrate the document context to the latest.
*/
migrateContext__() {
var _a;
if (this.context__.meta.fv === _DocumentReference.fileFormatVersion) return;
this.logger__.logMethod?.("migrateContext__");
if (this.context__.meta.fv > _DocumentReference.fileFormatVersion) {
this.logger__.accident("migrateContext__", "store_version_incompatible", this.context__.meta);
throw new Error("store_version_incompatible", { cause: this.context__.meta });
}
if (this.context__.meta.fv === 1) {
this.context__.meta.fv = 2;
}
if (this.context__.meta.fv === 2) {
if (this.context__.meta.schemaVer === void 0 || this.context__.meta.schemaVer === 0) {
this.context__.meta.schemaVer = 1;
}
delete this.context__.meta["ver"];
(_a = this.context__.meta).extra ?? (_a.extra = {});
this.context__.meta.fv = 3;
}
this.updated__();
}
/**
* Get nitrobase schema version
*
* @returns nitrobase schema version
*/
get schemaVer() {
return this.context__.meta.schemaVer ?? 1;
}
/**
* Set nitrobase schema version for migrate
*/
set schemaVer(ver) {
this.logger__.logMethodArgs?.("set schemaVer", { old: this.context__.meta.schemaVer, new: ver });
this.context__.meta.schemaVer = ver;
this.updated__();
}
/**
* Gets the freeze status of the document data.
*
* @returns `true` if the document data is frozen, `false` otherwise.
*
* @example
* ```typescript
* const isFrozen = documentRef.freeze;
* console.log(isFrozen); // Output: false
* ```
*/
get freeze() {
return this._freeze;
}
/**
* Sets the freeze status of the document data.
*
* @param value - The freeze status to set.
*
* @example
* ```typescript
* documentRef.freeze = true;
* console.log(documentRef.freeze); // Output: true
* ```
*/
set freeze(value) {
this.logger__.logMethodArgs?.("freeze changed", { value });
this._freeze = value;
}
/**
* Retrieves the document's data.
*
* @returns The document's data.
*
* @example
* ```typescript
* const documentData = documentRef.getData();
* ```
*/
getData() {
this.logger__.logMethod?.("getData");
return this.context__.data;
}
/**
* Retrieves the document's metadata.
*
* @returns The document's metadata.
*
* @example
* ```typescript
* const documentMeta = documentRef.getStoreMeta();
* ```
*/
getStoreMeta() {
this.logger__.logMethod?.("getStoreMeta");
return this.context__.meta;
}
/**
* Sets the document's data. replacing the existing data.
*
* @param data The new document data.
*
* @example
* ```typescript
* documentRef.replaceData({ a: 1, b: 2, c: 3 });
* ```
*/
replaceData(data) {
this.logger__.logMethodArgs?.("replaceData", data);
this.context__.data = data;
this.updated__();
}
/**
* Updates document's data by merging a partial update into the document's data.
*
* @param data The part of data to merge into the document's data.
*
* @example
* ```typescript
* documentRef.mergeData({ c: 4 });
* ```
*/
mergeData(data) {
this.logger__.logMethodArgs?.("mergeData", data);
Object.assign(this.context__.data, data);
this.updated__();
}
/**
* Requests the Alwatr Nitrobase to save the document.
* Saving may take some time in Alwatr Nitrobase due to the use of throttling.
*
* @example
* ```typescript
* documentRef.save();
* ```
*/
save() {
this.logger__.logMethod?.("save");
this.updated__();
}
/**
* Requests the Alwatr Nitrobase to save the document immediately.
*
* @example
* ```typescript
* documentRef.saveImmediate();
* ```
*/
saveImmediate() {
this.logger__.logMethod?.("saveImmediate");
this.updated__(
/* immediate: */
true
);
}
/**
* Retrieves the full context of the document.
*
* @returns The full context of the document.
*
* @example
* ```typescript
* const context = documentRef.getFullContext_();
* ```
*/
getFullContext_() {
this.logger__.logMethod?.("getFullContext_");
return this.context__;
}
/**
* Update the document metadata and invoke the updated callback.
* This method is throttled to prevent multiple updates in a short time.
*/
async updated__(immediate = false) {
this.logger__.logMethodArgs?.("updated__", { immediate, delayed: this.updateDelayed_ });
this.hasUnprocessedChanges_ = true;
if (immediate !== true && this.updateDelayed_ === true) return;
this.updateDelayed_ = true;
if (immediate === true || this.context__.meta.changeDebounce === void 0) {
await import_nanolib3.delay.immediate();
} else {
await import_nanolib3.delay.by(this.context__.meta.changeDebounce);
}
if (this.updateDelayed_ !== true) return;
this.updateDelayed_ = false;
this.refreshMetadata_();
if (this._freeze === true) return;
this.updatedCallback__(this);
}
/**
* Refresh/recalculate the document's metadata timestamp and revision.
*/
refreshMetadata_() {
this.logger__.logMethod?.("refreshMetadata_");
this.context__.meta.updated = Date.now();
this.context__.meta.rev++;
}
/**
* Retrieves the document's extra metadata.
*
* @returns The document's extra metadata.
*
* @example
* ```typescript
* const colExtraMeta = documentRef.getExtraMeta();
* ```
*/
getExtraMeta() {
this.logger__.logMethod?.("getExtraMeta");
return this.context__.meta.extra;
}
/**
* Sets/replace the document's extra metadata.
*
* @param extraMeta The new document's extra metadata.
*
* @example
* ```typescript
* documentRef.replaceExtraMeta({ a: 1, b: 2, c: 3 });
* ```
*/
replaceExtraMeta(extraMeta) {
this.logger__.logMethodArgs?.("replaceExtraMeta", extraMeta);
this.context__.meta.extra = extraMeta;
this.updated__();
}
/**
* Updates document's extra metadata by merging a partial update.
*
* @param extraMeta The part of extra metadata to merge into the document's extra metadata.
*
* @example
* ```typescript
* documentRef.mergeExtraMeta({ c: 4 });
* ```
*/
mergeExtraMeta(extraMeta) {
this.logger__.logMethodArgs?.("mergeExtraMeta", extraMeta);
Object.assign(this.context__.meta.extra, extraMeta);
this.updated__();
}
};
/**
* Alwatr nitrobase engine version string.
*/
_DocumentReference.version = "7.8.0";
/**
* Alwatr nitrobase engine file format version number.
*/
_DocumentReference.fileFormatVersion = 3;
var DocumentReference = _DocumentReference;
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
CollectionReference,
DocumentReference
});
//# sourceMappingURL=main.cjs.map