加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

TypeScript/Angular2中的DTO设计

发布时间:2020-12-17 07:11:44 所属栏目:安全 来源:网络整理
导读:我目前正在开发一个Angular 2应用程序.在开发过程中,我开始使用TypeScript类从 JSON创建对象,我通过HTTP或在表单中创建新对象时创建对象. 例如,该类可能看起来像这样. export class Product { public id: number; public name: string; public description:
我目前正在开发一个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
        }
    }
}

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

解决方法

您可以使用 property decorator:

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"}

(code in playground)

如果需要,可以使用在他们的示例中使用的the reflect-metadata,我使用DOT_INCLUDES注册表实现它,以便它可以在操场中很好地工作而无需额外的依赖项.

编辑

正如@Bergi评论的那样,您可以迭代包含而不是:

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;
}

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读