Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/strong-pigs-judge.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@rineex/ddd': minor
---

Add `Entity.toJSON()` to provide a single primitive-safe JSON object containing `id`, `createdAt`, and entity props.
21 changes: 21 additions & 0 deletions packages/ddd/src/domain/entities/__tests__/entity.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,27 @@ describe('entity', () => {
});
});

describe('toJSON', () => {
it('should return flattened primitive representation', () => {
const id = UUID.generate();
const createdAt = new Date('2023-01-01');
const user = new User({
props: { email: 'john@example.com', name: 'John Doe' },
createdAt,
id,
});

const json = user.toJSON();

expect(json).toEqual({
createdAt: createdAt.toISOString(),
email: 'john@example.com',
name: 'John Doe',
id: id.value,
});
});
});

describe('mutate', () => {
it('should update props and revalidate', () => {
const id = UUID.generate();
Expand Down
44 changes: 44 additions & 0 deletions packages/ddd/src/domain/entities/entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,39 @@ export abstract class Entity<ID extends EntityId, Props> {
this.validate();
}

private static normalize(value: unknown): unknown {
if (value == null) return value;

if (value instanceof Date) {
return value.toISOString();
}

if (
typeof value === 'string' ||
typeof value === 'number' ||
typeof value === 'boolean'
) {
return value;
}

if (Array.isArray(value)) {
return value.map(item => Entity.normalize(item));
}

if (typeof value === 'object') {
if ('toJSON' in value && typeof value.toJSON === 'function') {
return Entity.normalize(value.toJSON());
}

const obj = value as Record<string, unknown>;
return Object.fromEntries(
Object.entries(obj).map(([key, val]) => [key, Entity.normalize(val)]),
);
}

return String(value);
}

/**
* Compares entities by identity.
* In DDD, two entities are considered equal if their IDs match,
Expand All @@ -72,6 +105,17 @@ export abstract class Entity<ID extends EntityId, Props> {
return this.id.equals(other.id);
}

/**
* Converts the entity to a plain JSON-safe object with primitive values.
*/
public toJSON(): Record<string, unknown> {
return Entity.normalize({
...this.#props,
createdAt: this.createdAt,
id: this.id.value,
}) as Record<string, unknown>;
}

/**
* Converts the Entity into a plain Javascript object.
* Subclasses must implement this to explicitly control serialization,
Expand Down
Loading