Skip to content

Commit

Permalink
fix: entity data attribute type
Browse files Browse the repository at this point in the history
  • Loading branch information
tgallacher committed Dec 16, 2021
1 parent 8df0702 commit 55c2181
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 14 deletions.
6 changes: 3 additions & 3 deletions src/entity.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { Entity } from './entity';
describe('Entity', () => {
it("sets it's own id for new objects", () => {
class TestEntity extends Entity {}
const obj = new TestEntity();
const obj = new TestEntity({});

expect(obj.id).toBeString();
expect(obj.id.length).toBeGreaterThan(0);
Expand Down Expand Up @@ -35,7 +35,7 @@ describe('Entity', () => {
it('correctly compares two identical entities', () => {
class TestEntity extends Entity {}

const obj1 = new TestEntity();
const obj1 = new TestEntity({});

expect(obj1.equals(obj1)).toBeTrue();
});
Expand All @@ -45,7 +45,7 @@ describe('Entity', () => {

const preexistingId = uuid();
const obj1 = new TestEntity({ id: preexistingId });
const obj2 = new TestEntity();
const obj2 = new TestEntity({});

expect(obj1.equals(obj2)).toBeFalse();
});
Expand Down
19 changes: 8 additions & 11 deletions src/entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,36 +12,33 @@ export interface IEntity {
equals(object?: IEntity): boolean;
}

interface defaultConstructorData {
tenantId: string;
id: string;
}
type IBaseEntityData = Partial<{
tenantId: IEntity['tenantId'];
id: IEntity['id'];
}>;

/**
* An object whose definition is based on `identity` over just its attributes.
*
* Also known as `Reference Objects`.
*/
export abstract class Entity<
T extends Partial<defaultConstructorData> = Partial<defaultConstructorData>,
> implements IEntity
export abstract class Entity<T extends IBaseEntityData = IBaseEntityData>
implements IEntity
{
private readonly _id: IEntity['id'];
private readonly _tenantId: IEntity['tenantId'];

protected readonly _data: Omit<T, 'id' | 'tenantId'>;

// Make `id` optional accounting for re-consituting objects from persistence
constructor(data?: T) {
// Make `id` optional: allow for re-consituting objects from persistence
constructor(data: T) {
this._tenantId = data?.tenantId ?? '';
this._id = data?.id ?? uuid();

// remove captured fields, if they exist
delete data?.id;
delete data?.tenantId;

// @ts-expect-error
// fixme: check typing
this._data = data ?? {};
}

Expand Down

0 comments on commit 55c2181

Please sign in to comment.