首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >DDD:用JavaScript封装聚合根

DDD:用JavaScript封装聚合根
EN

Stack Overflow用户
提问于 2022-02-08 19:18:59
回答 1查看 362关注 0票数 0

我找不到任何清楚的示例,说明如何使用JavaScript/TypeScript正确封装聚合根(DDD)的内部状态来实现它。下面我就如何实现它提出一个建议。也许有人对如何改进这个解决方案有自己的想法:

代码语言:javascript
复制
import cloneDeep from 'clone-deep';
import { deepFreeze } from '../utils'; // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze

export class AggregateRoot<TEntityProps> {
  // TODO EntityId
  
  protected readonly props: TEntityProps

  constructor(props: TEntityProps) {
    /** Encapsulate aggregate's state from the outside world */
    this.props = cloneDeep<TEntityProps>(props)
  }
  
  /** Extract the state from an aggregate. 
   * 
   * Aggregate becomes unchangeable (read-only) after calling the flush method.
   * */
  public flush(): TEntityProps {
    return deepFreeze(this.props)
  }
}

// Usage
export class User extends AggregateRoot<UserProps> {
  constructor(props: UserProps) {
    super(props)
    
    // props validation here

  }

  get firstName() {
    return this.props.firstName
  }

  get lastName() {
    return this.props.lastName
  }

  get updatedAt() {
    return this.props.updatedAt
  }
}
EN

回答 1

Stack Overflow用户

发布于 2022-02-08 19:18:59

另一个变体是重写此方法:

代码语言:javascript
复制
  public flush(): TEntityProps {
    return deepFreeze(this.props)
  }

使用

代码语言:javascript
复制
  public snapshot(): TEntityProps {
    return cloneDeep(this.props)
  }

但我们需要知道,在这种情况下,我们增加了两次内存消耗。因此,我认为,它很可能适合于小型聚集体。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71039672

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档