UNPKG

ravendb

Version:
75 lines 2.64 kB
import { throwError } from "../../Exceptions/index.js"; import { TypeUtil } from "../../Utility/TypeUtil.js"; export class GenerateEntityIdOnTheClient { _conventions; _generateId; constructor(conventions, generateId) { this._conventions = conventions; this._generateId = generateId; } _getIdentityProperty(entityType) { return this._conventions.getIdentityProperty(entityType); } /** * Attempts to get the document key from an instance */ tryGetIdFromInstance(entity, idCallback) { if (!entity) { throwError("InvalidArgumentException", "Entity cannot be null or undefined."); } const resultCallback = (result) => { if (idCallback) { idCallback(result); } }; try { const docType = TypeUtil.findType(entity, this._conventions.knownEntityTypes); const identityProperty = this._getIdentityProperty(docType); if (identityProperty) { const value = entity[identityProperty]; if (typeof (value) === "string") { resultCallback(value); return true; } } resultCallback(null); return false; } catch { throwError("InvalidOperationException", "Error trying to get ID from instance."); } } async getOrGenerateDocumentId(entity) { let id; this.tryGetIdFromInstance(entity, (idVal) => id = idVal); // Generate the key up front if (!id) { id = await this._generateId(entity); } if (id && id.startsWith("/")) { throwError("InvalidOperationException", "Cannot use value '" + id + "' as a document id because it begins with a '/'"); } return id; } async generateDocumentKeyForStorage(entity) { const id = await this.getOrGenerateDocumentId(entity); this.trySetIdentity(entity, id); return id; } /** * Tries to set the identity property */ trySetIdentity(entity, id, isProjection = false) { const docType = TypeUtil.findType(entity, this._conventions.knownEntityTypes); const identityProperty = this._conventions.getIdentityProperty(docType); if (!identityProperty) { return; } if (isProjection && entity[identityProperty]) { // identity property was already set return; } entity[identityProperty] = id; } } //# sourceMappingURL=GenerateEntityIdOnTheClient.js.map