如何使用express和typeorm正确更新实体

问题描述 投票:2回答:1

我正在寻找用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个回答
0
投票

你可以关注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很容易推出自己的版本,这将使验证更具说明性。

© www.soinside.com 2019 - 2024. All rights reserved.