仅当登录的用户具有与实体相同的ID时,我才会序列化实体User的属性“ email”。
实体用户:
@Entity()
@Exclude()
export class User {
@Expose()
@PrimaryGeneratedColumn("uuid")
id: string;
@Expose() // Only if logged user == this
@Column({nullable: true, default: null})
public email: string;
@Expose()
@Column({nullable: true, default: null})
public username: string;
@Column({nullable: true, default: null})
public password: string;
@CreateDateColumn()
public create_at: Date;
@UpdateDateColumn()
public update_at: Date;
}
答案 0 :(得分:1)
您可以执行以下操作:
@Entity()
@Exclude()
export class User {
@Expose()
@PrimaryGeneratedColumn("uuid")
id: string;
@Column({nullable: true, default: null})
public email: string;
public connectedUser: string?;
@Expose({ name: 'email'}) // Only if logged user
public get hideableEmail(): string? {
if(this.email === this.connectedUser) {
retun this.email;
}
return null;
}
@Expose()
@Column({nullable: true, default: null})
public username: string;
@Column({nullable: true, default: null})
public password: string;
@CreateDateColumn()
public create_at: Date;
@UpdateDateColumn()
public update_at: Date;
}
答案 1 :(得分:1)
没有直接的方法可以基于对象本身有条件地排除属性。您可以使用分组来控制曝光:
@Expose({ groups: ['owner'] })
@Column({nullable: true, default: null})
public email: string;
,然后在控制器中根据您的条件添加组:
const groups = [];
if (isCurrentUser) {
groups.push('owner');
}
classToPlain(user, { groups })