class 序列化在 nestjs 中不起作用

class serialization not working in nestjs

我有一个简单的用户模型,我想从中排除密码。使用 official docs and 我试图让它工作,但这似乎不起作用,因为我收到类似这样的回复。

[
  {
    "$__": {
      "strictMode": true,
      "selected": {},
      "getters": {},
      "_id": {
        "_bsontype": "ObjectID",
        "id": {
          "type": "Buffer",
          "data": [
            94,
            19,
            73,
            179,
            3,
            138,
            216,
            246,
            182,
            234,
            62,
            37
          ]
        }
      },
      "wasPopulated": false,
      "activePaths": {
        "paths": {
          "password": "init",
          "email": "init",
          "name": "init",
          "_id": "init",
          "__v": "init"
        },
        "states": {
          "ignore": {},
          "default": {},
          "init": {
            "_id": true,
            "name": true,
            "email": true,
            "password": true,
            "__v": true
          },
          "modify": {},
          "require": {}
        },
        "stateNames": [
          "require",
          "modify",
          "init",
          "default",
          "ignore"
        ]
      },
      "pathsToScopes": {},
      "cachedRequired": {},
      "session": null,
      "$setCalled": [],
      "emitter": {
        "_events": {},
        "_eventsCount": 0,
        "_maxListeners": 0
      },
      "$options": {
        "skipId": true,
        "isNew": false,
        "willInit": true
      }
    },
    "isNew": false,
    "_doc": {
      "_id": {
        "_bsontype": "ObjectID",
        "id": {
          "type": "Buffer",
          "data": [
            94,
            19,
            73,
            179,
            3,
            138,
            216,
            246,
            182,
            234,
            62,
            37
          ]
        }
      },
      "name": "Kamran",
      "email": "kamran@example.com",
      "password": "Pass1234",
      "__v": 0
    },
    "$locals": {},
    "$init": true
  }
]

这是我的模型。我正在使用 TypegooseMongoose 也是如此。

export class User extends Typegoose {
  @Transform((value) => value.toString(), { toPlainOnly: true })
  _id: string;

  @prop({ required: true })
  public name!: string;

  @prop({ required: true })
  public email!: string;

  @Exclude({ toPlainOnly: true })
  @prop({ required: true })
  public password!: string;
}

我的用户服务

@Injectable()
export class UserService {
  constructor(@InjectModel(User) private readonly user: ReturnModelType<typeof User>) {}

  async getUsers() {
    return this.user.find().exec();
  }
}

和用户控制器

@Controller('users')
@UseInterceptors(ClassSerializerInterceptor)
export class UserController {
  constructor(private readonly userService: UserService) {}

  @Get()
  async index() : Promise<User[] | []> {
    return this.userService.getUsers();
  }
}

我尝试按照描述使用我的自定义拦截器 but that didn't work so i changed it to below code as given here

@Injectable()
export class TransformInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    return next.handle().pipe(map(data => classToPlain(this.transform(data))));
  }

  transform(data) {
    const transformObject = (obj) => {
      const result = obj.toObject();
      const classProto = Object.getPrototypeOf(new User());
      Object.setPrototypeOf(result, classProto);
      return result;
    }

    return Array.isArray(data) ? data.map(obj => transformObject(obj)) : transformObject(data);
  }
}

现在可以使用了,但是代码不是通用的。有什么办法让它通用吗?

我想我已经确定了问题所在,但不确定为什么会发生这种情况。所以这就是问题所在,如果我 return class 的实例,那么序列化工作,但如果我只是 return 普通数据库响应,则会发生上述问题。所以我所做的是将 toObjecttransform 方法中的响应对象的原型更新给我的用户 class。这是代码。

User Model

@modelOptions({
  schemaOptions: {
    toObject: {
      transform: function(doc, ret, options) {
        Object.setPrototypeOf(ret, Object.getPrototypeOf(new User()));
      }
    },
  },
})
export class User {
  @Transform((value) => value.toString(), { toPlainOnly: true })
  public _id: string;

  @prop({ required: true })
  public name!: string;

  @prop({ required: true })
  public email!: string;

  @Exclude({ toPlainOnly: true })
  @prop({ required: true })
  public password!: string;
}

TransformInterceptor

@Injectable()
export class TransformInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    return next.handle().pipe(map(data => classToPlain(this.transform(data))));
  }

  transform(data) {
    return Array.isArray(data) ? data.map(obj => obj.toObject()) : data.toObject();
  }
}

现在,如果您只用 @UseInterceptors(TransformInterceptor) 装饰您的控制器或方法,它将完美运行。这是一个 typegoose 解决方案,但它与 mongoose 的工作方式相同。

@kamran-arshad 的回答帮助我找到了使用 typegoose 实现预期结果的合适方法。您可以使用装饰器 @modelOptions() 并向其传递一个具有生成 JSON.

函数的对象
@modelOptions({
  toJSON: {
    transform: function(doc, ret, options) {
      delete ret.password;
      return ret;
    }
  }
})
export class User extends Typegoose {
@prop({required: true})
name!: string;

@prop({required: true})
password!: string;
}

它并不完美,因为来自 class-transform 的装饰器没有按预期工作,但它完成了工作。另外,你应该避免使用 ClassSerializerInterceptor 因为它会给出与 OP 提到的相同的结果。

为了避免 Mongoose 引起的任何背痛和头痛, 我建议使用 plainToClass 以获得完整的 mongoose/class-transform 兼容性,并避免必须进行自定义覆盖来克服此问题。

例如,将此添加到您的服务中:

async validateUser(email: string, password: string): Promise<UserWithoutPassword | null> {
    const user = await this.usersService.findOne({ email });

    if (user && await compare(password, user.password))
    {
        return plainToClass(UserWithoutPassword, user.toObject());
    }

    return null;
}

这样你就可以使用 @Exclude() 和其他装饰器

来源:

这是我的实现,所有装饰器都可以在不需要 ClassSerializerInterceptor

的情况下工作
PersonSchema.methods.toJSON = function () {
  return plainToClass(Person, this.toObject());
};

import { Exclude, Expose } from "class-transformer";

export class UserSerializer {

    @Expose()
    email: string;
    @Expose()
    fullName: string;
    @Exclude()
    password: string;

    @Expose()
    username: string;
}

 @Post("new")
    async createNewAccount(@Body() body: CreateUserDTO) {
        return plainToClass(UserSerializer, await (await this.authService.createNewUser(body)).toJSON())
    }