【问题标题】:What is the best way to update different properties?更新不同属性的最佳方法是什么?
【发布时间】:2020-11-26 23:16:31
【问题描述】:

我正在使用基于Express 的Restify 构建API。我正在使用Typeorm,我想知道更新来自用户输入的不同属性的最佳方法是什么。

基本上我有这样的路线:

server.put('/users/:id', errorHandler(update));

触发此方法:

const update = async (req: Request, res: Response) => {
    const user = { ...req.body, id: req.params.id } as User;
    res.send(await userService.update(user));
}

如您所见,我使用扩展运算符创建了一个User 实体。然后,在userService.update 里面我有以下内容:

export const update = async (user: User): Promise<User> => {
    const repository = getRepository(User);
    const entity = await repository.findOne({ id: user.id });
    if (!entity) throw new errors.ResourceNotFoundError(`There is no user with id of ${user.id}`);

    Object.assign(entity, user, { id: entity.id, chat_id: entity.chat_id, project_id: entity.project_id, deleted: false });
    return await repository.save(entity);
}

如您所见,我想防止API消费者提供的数据会替换一些重要的属性,例如:id, chat_id, project_id, deleted,所以我使用Object.assign的方法来实现这一点。

这是个好方法吗?您有什么改进建议?

【问题讨论】:

    标签: node.js typescript express typeorm restify


    【解决方案1】:

    您可以像这样使用 typeorm 的 update 方法,它会部分更新您作为第二个参数提供的值。

    // this will find a user with id ${user.id} and will only 
    // change the fields that is specified in the user object
    await repository.update(user.id, user);
    
    // check if updated for debugging 
    const updatedUser = await repository.findOne(user.id);
    console.log(updatedUser, null, 2) 
    

    如果你想在db中创建一个现有用户的新记录,那么你只需要改变它的id。这样做

    1. 深度克隆对象,因此会有另一个具有新引用的用户对象
    2. 从深层克隆对象中删除 id 字段,然后使用 insert
    // Deep clone user object
    const clonedUser = JSON.parse(JSON.stringify(user))
    // Delete id field from the deep clone 
    delete clonedUser.id;
    // create a new user with different id
    await repository.insert(clonedUser);
    
    

    【讨论】:

    • 所以我想我应该为insert 做同样的事情?因为,如果我传递包含id 的数据,save 方法将尝试更新而不是插入。您能否也扩展您对插入的答案,并展示如何正确返回插入/更新的数据?
    • 您要添加新记录还是更新现有记录?
    • 我想添加一条新记录,但假设提供的数据还包含id 属性,.save 方法将尝试使用提供的 id 更新记录。
    • 我的理解是你想要一条新记录和旧记录相等,所以你要添加的记录是旧记录的克隆?
    • 是的,这是我想管理的可能情况。基本上:数据库已经包含一条 id 为 5 的记录,用户通过 API 调用传递了一条具有字段 id 5 的新记录。我想了解如何在不考虑用户传递的 id 的情况下插入新记录,如该列是自动递增的。
    【解决方案2】:

    您可以过滤您的重要属性。

    并将用户 ID 传递给您的 userService 的 update 方法。

    const { id, chat_id, project_id, deleted, ...user } = req.body;
    const { id } = req.params;
    
    res.send(await userService.update(id, user));
    

    这将确保user 对象没有属性(这很重要)。

    您可以更改您的update 方法,如下所示:

    export const update = (userId: string, user: User): Promise<User> => {
        return getRepository(User).update(userId, user);
    }
    

    【讨论】:

      猜你喜欢
      • 2013-01-24
      • 1970-01-01
      • 1970-01-01
      • 2016-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-16
      • 2014-04-17
      相关资源
      最近更新 更多