@0xc/transient 中文文档教程

发布于 3年前 浏览 31 更新于 3年前

 npm(作用域)”></a> 
  <a href= npm  GitHub 问题 GitHub 拉取请求 Dependencies

@0xc/transient

这个包提供了一个 @transient 装饰器,类似于 Java 中的 transient 关键字。

使用本机 JSON.stringify(object) 时,使用 @transient 运算符标记类中的属性将忽略该属性的序列化。

如果您希望编辑通过网络传输的对象的属性,例如使用 fetch 和其他使用 JSON.stringify 的对象,这将很有用。

example

要开始使用 transient 装饰器,您可以从库中导入它:

import { transient } from "@0xc/transient";

export class UserDto {
    public firstName: string;

    public lastName: string;

    public email: string;

    @transient()
    public password: string;

    public static fromModel(userModel: UserModel): UserDto {
        const userDto = new UserDto();
        this.firstName = userModel.firstName;
        this.lastName = userModel.lastName;
        this.email = userModel.email;
        this.password = userModel.password;
        return userDto;
    }
}

在这种情况下,我们有一个 User DTO,它在调用 userDto.toJSON()。 也许这是使用后端服务,我们希望在将响应序列化回用户时不返回此字段。

app.get("/user", (req, res) => {
    const userModel = UserRepository.findOne(req.session.id);
    const userDto = UserDto.fromModel(userModel);
    res.send(userDto);
});

Ta-da! 现在响应应该如下所示:

{
    "firstName": "Ricky",
    "lastName": "Bobby",
    "email": "shake@bake.net"
}

npm (scoped) npm GitHub issues GitHub pull requests Dependencies

@0xc/transient

This package provides a @transient decorator, similar to the transient keyword in Java.

Marking a property in a class with the @transient operator will ignore serialization of that property when using the native JSON.stringify(object).

This is useful if you would prefer to redact properties for objects going over the wire, such as with fetch and others which make use of JSON.stringify.

example

To get started using the transient decorator, you can import it from the library:

import { transient } from "@0xc/transient";

export class UserDto {
    public firstName: string;

    public lastName: string;

    public email: string;

    @transient()
    public password: string;

    public static fromModel(userModel: UserModel): UserDto {
        const userDto = new UserDto();
        this.firstName = userModel.firstName;
        this.lastName = userModel.lastName;
        this.email = userModel.email;
        this.password = userModel.password;
        return userDto;
    }
}

In this scenario, we have a User DTO which will no longer serialize when calling userDto.toJSON(). Perhaps this is used a backend service which we would prefer to not return this field when serializing a response back to users.

app.get("/user", (req, res) => {
    const userModel = UserRepository.findOne(req.session.id);
    const userDto = UserDto.fromModel(userModel);
    res.send(userDto);
});

Ta-da! Now the response should look like:

{
    "firstName": "Ricky",
    "lastName": "Bobby",
    "email": "shake@bake.net"
}
更多

友情链接

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文