【问题标题】:Hide sensible data from the user in the response NestJS/Mongoose在响应 NestJS/Mongoose 中隐藏用户的敏感数据
【发布时间】:2022-03-01 21:33:25
【问题描述】:

我在上周开始使用 nest,即使我发现它非常有用,也有一些我无法从经典的 Express/Mongoose 应用程序中复制的东西。 其中之一是在返回时提供敏感数据作为密码。

例如在Express/Mongoose 应用程序中,我将这样做以清理用户可以看到的内容:

const { Schema, model } = require("mongoose");

const UserSchema = new Schema({
  name: {
    type: String,
    required: [true, "Name is required"],
  },
  email: {
    type: String,
    required: [true, "Email is required"],
    unique: true,
  },
  password: {
    type: String,
    required: [true, "Password is required"],
  },
  img: {
    type: String,
  },
  rol: {
    type: String,
    required: true,
    emun: ["ADMIN_ROL", "USER_ROL"],
  },
  state: {
    type: Boolean,
    default: true,
  },
  google: {
    type: Boolean,
    default: false,
  },
});

UserSchema.methods.toJSON = function () {
  const { __v, _id, password, ...user } = this.toObject();
  user.uid = _id;
  return user;
};

module.exports = model("Users", UserSchema);

如您所见,我实现了该类的方法来清理user 对象并返回安全且干净的响应。

同时使用NestJS/Mongoose 创建用户模式的类似方法是这样的:

import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';

export type UserDocument = User & Document;

@Schema()
export class User {
  @Prop({
    required: [true, 'Name is required'],
  })
  name: string;
  @Prop({
    required: [true, 'Password is required'],
  })
  password: string;
  @Prop()
  img: string;
  @Prop({
    required: true,
    enum: ['ADMIN_ROL', 'USER_ROL'],
  })
  rol: string;
  @Prop({
    default: true,
  })
  state: boolean;
  @Prop({
    default: false,
  })
  google: boolean;
}

export const UserSchema = SchemaFactory.createForClass(User);

非常基础,只是在 NestJS 文档中使用。

使用 Nest 实现相同结果的最佳方法是什么?

我也想问你任何与巢一起工作的博客/youtuber,我们将不胜感激

【问题讨论】:

    标签: node.js mongodb express mongoose nestjs


    【解决方案1】:

    Nest.js 提供来自 OpenAPI 规范的 Mapped Types

    您可以使用PartialTypeOmitTypePickType 函数创建DTOs。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-03-18
      • 1970-01-01
      • 1970-01-01
      • 2021-02-25
      • 1970-01-01
      • 1970-01-01
      • 2020-04-29
      相关资源
      最近更新 更多