TypeScript/Angular2中的DTO设计

DaS*_*Sch 7 software-design restful-architecture typescript ecmascript-6

我目前正在开发一个Angular 2应用程序.在开发过程中,我开始使用TypeScript类从JSON创建对象,我通过HTTP或在表单中创建新对象时创建对象.

例如,该类可能看起来像这样.

export class Product {
    public id: number;
    public name: string;
    public description: string;
    public price: number;
    private _imageId: number;
    private _imageUrl: string;

    constructor(obj: Object = {}) {
        Object.assign(this, obj);
    }

    get imageId(): number {
        return this._imageId;
    }
    set imageId(id: number) {
        this._imageId = id;
        this._imageUrl = `//www.example.org/images/${id}`;
    }

    get imageUrl(): string {
        return this._imageUrl;
    }

    public getDTO() {
        return {
            name: this.name,
            description: this.description,
            imageId: this.imageId,
            price: this.price
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

到目前为止,上面显示的这个解决方 但现在让我们假设对象中有更多属性,我想要一个干净的DTO(例如没有私有属性),通过POST将此Object发送到我的服务器.一个更通用的getDTO()功能怎么样?我想避免列出很长的财产分配清单.我在考虑为属性使用装饰器.但我真的不知道如何使用它们来过滤DTO的属性.

Nit*_*mer 7

您可以为此使用属性装饰器

const DOT_INCLUDES = {};

function DtoInclude(proto, name) {
    const key = proto.constructor.name;
    if (DOT_INCLUDES[key]) {
        DOT_INCLUDES[key].push(name);
    } else {
        DOT_INCLUDES[key] = [name];
    }
}

class A {
    @DtoInclude
    public x: number;
    public y: number;

    @DtoInclude
    private str: string;

    constructor(x: number, y: number, str: string) {
        this.x = x;
        this.y = y;
        this.str = str;
    }

    toDTO(): any {
        const includes: string[] = DOT_INCLUDES[(this.constructor as any).name];
        const dto = {};

        for (let key in this) {
            if (includes.indexOf(key) >= 0) {
                dto[key] = this[key];
            }
        }

        return dto;
    }
}

let a = new A(1, 2, "string");
console.log(a.toDTO()); // Object {x: 1, str: "string"}
Run Code Online (Sandbox Code Playgroud)

操场上的代码

如果你愿意,你可以使用他们示例中使用的反射元数据,我用DOT_INCLUDES注册表实现了它,这样它就可以在操场上很好地工作,而无需额外的依赖。


编辑

正如@Bergi 评论的那样,您可以迭代includes而不是this

toDTO(): any {
    const includes: string[] = DOT_INCLUDES[(this.constructor as any).name];
    const dto = {};

    for (let ket of includes) {
        dto[key] = this[key];
    }

    return dto;
}
Run Code Online (Sandbox Code Playgroud)

这确实更有效,更有意义。

  • 我猜`for (let key of includes)`更简单,性能更好 (2认同)