0.1.0 • Published 3 years ago

@0xc/transient v0.1.0

Weekly downloads
-
License
MIT
Repository
-
Last release
3 years ago

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