【发布时间】: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