4lessandrodev / type-ddd

This package provide utils files and interfaces to assistant build a complex application with domain driving design.
https://www.npmjs.com/package/@type-ddd/core
MIT License
250 stars 13 forks source link

Converting circular structure to JSON when use `toObject()` #414

Open GaetanCottrez opened 1 month ago

GaetanCottrez commented 1 month ago

Describe the bug

I obtained this error :

TypeError: Converting circular structure to JSON
        --> starting at object with constructor 'User'
        |     property '_domainEvents' -> object with constructor 'TsEvents'
        --- property 'aggregate' closes the circle
        at JSON.stringify (<anonymous>)

Because my aggregate ChatConversation contains arrays of aggregate in props :

export interface ConversationProps {
    id?: UID;
    users: User[]; // User is an Aggregate
    messages: ChatMessage[]; // ChatMessage is an Aggregate
    isReadByUserId: string[];
    createdAt?: Date;
    updatedAt?: Date;
}

And an aggregate contains a circular ref in _domainEvents > aggregate. For example :

User {
  props: {
    createdAt: 2022-01-01T00:00:00.000Z,
    updatedAt: 2022-01-01T00:00:00.000Z,
    id: [ID],
    name: 'John Doe',
    email: 'john@doe.com'
  },
  validator: Validator {},
  util: Utils {},
  parentName: 'Entity',
  config: { disableGetters: false, disableSetters: true },
  _id: ID {
    _value: 'valid_user_id',
    _isNew: false,
    _createdAt: 2024-07-16T17:17:03.392Z,
    MAX_SIZE: 16
  },
  autoMapper: AutoMapper { validator: Validator {} },
  _domainEvents: TsEvents {
    aggregate: [Circular *1],
    _metrics: [Object],
    _events: [],
    totalDispatched: 0
  },
  _dispatchEventsAmount: 0
}

I located the problem in the package rich-domain in the file utils/validator.ts: https://github.com/4lessandrodev/rich-domain/blob/9764adf70549440dfc4e0058a4a3bb4011e3a92e/lib/utils/validator.ts#L40

If i used the package npm flatted for stringify, the problem not appears

For solved the problem, modify the file node_modules/.pnpm/rich-domain@1.23.2/node_modules/rich-domain/utils/validator.js and add the line const {stringify} = require('flatted'); at the top file.

And replace the line 41 if (JSON.stringify(props) === JSON.stringify({}))) to if (stringify(props) === tringify({})) and the test passed !

I create a pull request for the package rich-domain to solve it : https://github.com/4lessandrodev/rich-domain/pull/170

When you merged the pull request and increment version of rich-domain, up the version of rich-domain in type-ddd

To Reproduce I prepared a repository to reproduce the problem : https://github.com/GaetanCottrez/issue-type-ddd-json-stringify

Screenshots https://github.com/user-attachments/assets/c5bbe52a-b0d0-4829-b553-f8e493aa168c

4lessandrodev commented 1 month ago

Hey @GaetanCottrez , very good and thank you for your contribution!!!