domain-objects
Version:
A simple, convenient way to represent domain objects, leverage domain knowledge, and add runtime validation in your code base.
40 lines • 1.74 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.refByPrimary = void 0;
const helpful_errors_1 = require("helpful-errors");
/**
* creates a reference to a domain object by its primary key
*
* extracts only the primary key properties from a domain object instance
*
* note
* - you may need to explicitly annotate the type for proper inference
* - e.g., `const ref = refByPrimary<typeof SeaTurtle>(turtle)`
* - automatic resolution of the relationship between instance and class.static properties is not yet possible in TypeScript
*
* @example
* ```ts
* const turtle = new SeaTurtle({ uuid: '1', seawaterSecurityNumber: '821', name: 'Crush' });
* const ref = refByPrimary<typeof SeaTurtle>(turtle);
* // ref = { uuid: '1' }
* ```
*/
const refByPrimary = (instance) => {
// get the domain object constructor
const DomainObjectConstructor = instance.constructor;
const primaryKeys = DomainObjectConstructor?.primary;
if (!primaryKeys)
throw new helpful_errors_1.UnexpectedCodePathError('can not create refByPrimary on a dobj which does not declare its .primary keys', { dobj: DomainObjectConstructor?.name, primaryKeys });
// extract only the primary key properties from the instance
const ref = {};
for (const key of primaryKeys) {
const value = instance[key];
if (value === undefined) {
throw new helpful_errors_1.BadRequestError(`refByPrimary: primary key '${key}' is undefined; primary keys must have defined values at reference time.`, { dobj: DomainObjectConstructor?.name, key });
}
ref[key] = value;
}
return ref;
};
exports.refByPrimary = refByPrimary;
//# sourceMappingURL=refByPrimary.js.map