网站搜索

javascript - 在 Clean Architecture 的 Node.js 服务器中映射 DTO 和实体的最佳方法


我正在使用Typescript/node.js学习清洁架构,并且在寻找将DTO(数据传输对象)和领域实体映射的最佳方法时遇到了困难。

DTO 用于在表示层(网络服务器)和应用层(用例)之间传输数据。

我在网上找到了许多资源,建议在各种语言中使用各种设计模式来实现这一点:

  • 映射器(虽然它不是一种设计模式)
  • 工厂
  • 建设者
  • ...

在他的《Clean Architecture》一书中,Robert C. Martin 谈到了“适配器”,但我找不到任何明确的实现示例。

长期开发中最好的、最准确的设计决策会是什么?

基础代码

用户 DTO

interface IUserDTO {

    id: number;
    firstName: string;
    lastName: string;
    email: string;
    age: number;

}

用户实体

interface IUser {

    getId(): string;

    setFirstName(firstName: string): void;
    getFirstName(): string;

    setLastName(lastName: string): void;
    getLastName(): string;

    setEmail(email: string): void;
    getEmail(): string;

    setAge(age: number): void;
    getAge(): number;
    
}

class User implements IUser {

    private _id: string;
    private _firstName:string;
    private _lastName: string;
    private _email: string;
    private _age: number;

    getId(): string {
        return this._id;
    }
    
    setFirstName(firstName: string): void {
        this._firstName = firstName;
    }

    getFirstName(): string {
        return this._firstName;
    }

    setLastName(lastName: string): void {
        this._lastName = lastName;
    }

    getLastName(): string {
        return this._lastName;
    }
        
    setEmail(email: string): void {
        this._email = email;
    }
    
    getEmail(): string {
        return this._email;
    }

    setAge(age: number): void {
        this._age = age;
    }

    getAge(): number {
        return this._age;
    }

}

提议:针对接口实现映射器

但是,虽然它被普遍采用,它是一个可接受的设计模式吗?

class UserMapper implements IToDtoMappable<IUser, IUserDto> {

    toDto(entity: IUser): IUserDto {
        const dto: IUserDto = {
            id: entity.getId(),
            firstName: entity.getFirstName(),
            lastName: entity.getLastName(),
            email: entity.getEmail(),
            age: entity.getAge(),
        };
        return dto;
    }

}