【问题标题】:How to correctly update an entity with express and typeorm如何使用 express 和 typeorm 正确更新实体
【发布时间】:2019-09-01 21:16:54
【问题描述】:

我正在寻找使用 typeorm 和 express 更新 User 实体的最佳方法。

我有这样的东西(我已经减少了,但是还有很多其他属性):

class User {
  id: string;
  lastname: string;
  firstname: string;
  email: string;
  password: string;
  isAdmin: boolean;
}

我有一个更新用户属性的路径,例如:

app.patch("/users/me", ensureAuthenticated, UserController.update);

现在(这是我的问题),如何正确更新用户?我不希望用户能够将自己添加为管理员。

所以我有:

export const update = async (req: Request, res: Response) => {
  const { sub } = res.locals.token;
  const { lastname, firstname, phone, email } = req.body;

  const userRepository = getRepository(User);
  const currentUser = await userRepository.findOne({ id: sub });

  const newUserData: User = {
    ...currentUser,
    lastname: lastname || currentUser.lastname,
    firstname: firstname || currentUser.firstname,
    phone: phone || currentUser.phone,
    email: email || currentUser.email
  };

  await userRepository
    .update({ id: sub }, newUserData)
    .then(r => {
      return res.status(204).send();
    })
    .catch(err => {
      logger.error(err);
      return res.status(500).json({ error: "Error." });
    });
};

这样,我肯定会更新正确的属性,而用户无法更新管理员。 但是我发现创建一个新对象并填写信息非常冗长。

你有更好的方法吗? 谢谢。

【问题讨论】:

    标签: node.js api express typeorm


    【解决方案1】:

    您可以关注DTO pattern

    例如:

    class UserDto {
        // define properties
        constructor(data: any) {
            // validate data
            ...
        }
    }
    
    const userDto = new UserDto(req.body);                                          
    
    await userRepository
        .update({ id: sub }, userDto)
        .then(r => {
            ...
        })
        .catch(err => {
            ...
        });
    

    nestjs 框架有一个good example 说明如何设置 DTO 模式。但是使用class-validatorclass-transformer 很容易实现自己的验证,这将使验证更具声明性。

    【讨论】:

    • 但是当你使用带有 TypeORM 的 Nest 时呢?那么实体和 DTO 是单独的类,您需要一种方法将实体与 DTO 中的数据合并,然后再将它们保存到存储库中。
    • 是的,在这种情况下,您需要在保存之前将 DTO 类转换为实体类。
    猜你喜欢
    • 2020-12-22
    • 1970-01-01
    • 2018-09-10
    • 1970-01-01
    • 1970-01-01
    • 2021-12-21
    • 2013-05-07
    • 2021-06-05
    • 1970-01-01
    相关资源
    最近更新 更多