domain-objects
Version:
A simple, convenient way to represent domain objects, leverage domain knowledge, and add runtime validation in your code base.
45 lines • 2.68 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.getPrimaryIdentifier = void 0;
const error_fns_1 = require("@ehmpathy/error-fns");
const type_fns_1 = require("type-fns");
const assertDomainObjectIsSafeToManipulate_1 = require("../constraints/assertDomainObjectIsSafeToManipulate");
const DomainEntity_1 = require("../instantiation/DomainEntity");
const DomainEvent_1 = require("../instantiation/DomainEvent");
const DomainLiteral_1 = require("../instantiation/DomainLiteral");
const DomainObject_1 = require("../instantiation/DomainObject");
const DomainEntityPrimaryKeysMustBeDefinedError_1 = require("./DomainEntityPrimaryKeysMustBeDefinedError");
/**
* Extracts an object that identifies the domain object via primary key, for DomainEntity, DomainEvent, or DomainLiteral.
*
* Uses the definition of a DomainEntity, DomainEvent, or DomainLiteral in order to extract the primary key of the dobj, generically.
*/
const getPrimaryIdentifier = (obj) => {
var _a;
// make sure its an instance of DomainObject
if (!(obj instanceof DomainObject_1.DomainObject))
throw new Error('getUniqueIdentifier called on object that is not an instance of a DomainObject. Are you sure you instantiated the object? (Related: see `DomainObject.nested`)');
// make sure that its safe to manipulate
(0, assertDomainObjectIsSafeToManipulate_1.assertDomainObjectIsSafeToManipulate)(obj);
// handle DomainEntity, DomainEvent, and DomainLiteral
if (obj instanceof DomainEntity_1.DomainEntity ||
obj instanceof DomainEvent_1.DomainEvent ||
obj instanceof DomainLiteral_1.DomainLiteral) {
const className = obj.constructor.name;
const primaryKeys = obj.constructor.primary;
if (!primaryKeys)
throw new DomainEntityPrimaryKeysMustBeDefinedError_1.DomainEntityPrimaryKeysMustBeDefinedError({
entityName: className,
nameOfFunctionNeededFor: 'getPrimaryIdentifier',
});
const primary = (0, type_fns_1.pick)(obj, primaryKeys.flat());
return Object.keys(primary).length ? primary : undefined; // if no primary found in instance -> undefined
}
// throw error we get here, this is unexpected
throw new error_fns_1.UnexpectedCodePathError('unexpected domain object type for getUniqueIdentifier. expected DomainLiteral, DomainEntity, or DomainEvent', {
dobjClass: (_a = obj === null || obj === void 0 ? void 0 : obj.constructor) === null || _a === void 0 ? void 0 : _a.name,
dobj: obj,
});
};
exports.getPrimaryIdentifier = getPrimaryIdentifier;
//# sourceMappingURL=getPrimaryIdentifier.js.map