Class-transformer: @Exclude based on condition

Created on 6 Mar 2019  路  4Comments  路  Source: typestack/class-transformer

Hi,

Is it possible to exclude a property using @Exclude based on a certain condition?

Example

Lets say I have the following class, which represents an error response from an API.

export class ErrorResponse {
    error: string;
    stackTrace: string[];

    constructor(error: string, stackTrace: string[]) {
        this.error = error;
        this.stackTrace = stackTrace;
    }
}

Let's say I would like to exclude the stackTrace property if process.env.NODE_ENV === 'production'.

I figured I could use @Transform, and simply mask the property if the above condition is true, but I'm wondering whether this is the way to go:

export class ErrorResponse {
    error: string;

    @Transform(value => process.env.NODE_ENV === 'production' ? [] : value)
    stackTrace: string[];

    constructor(error: string, stackTrace: string[]) {
        this.error = error;
        this.stackTrace = stackTrace;
    }
}

Is there a recommended way to do what I'm trying to achieve?

question

Most helpful comment

You could do something like this:

const ProductionExclude = process.env.NODE_ENV === 'production' ?
    () => () => {} :
    Exclude;

class ErrorResponse {
    @ProductionExclude()
    stackTrack: string[];
}

All 4 comments

You could do something like this:

const ProductionExclude = process.env.NODE_ENV === 'production' ?
    () => () => {} :
    Exclude;

class ErrorResponse {
    @ProductionExclude()
    stackTrack: string[];
}

Hey @ERPedersen, if @kaleb's answer worked for you, would you mind closing this issue? I'm not a maintainer of this package but am trying to get some issues closed while the maintainers are away.

@alexpls thanks for doing that. Where are the maintainers?

This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

rmindel picture rmindel  路  5Comments

NathanHazout picture NathanHazout  路  5Comments

AckerApple picture AckerApple  路  5Comments

NoNameProvided picture NoNameProvided  路  5Comments

ceopaludetto picture ceopaludetto  路  3Comments