TypeORM:更新项目并返回它

时间:2017-12-13 12:15:34

标签: rest orm api-design typeorm

据我所知,在更新项目后返回项目是最佳做法。 TypeORM' updateById返回void,而不是更新的项目。

我的问题:是否可以在一行中更新并返回修改后的项目?

到目前为止我尝试了什么:

await this.taskRepository.updateById(id, { state, dueDate });
return this.taskRepository.findOne({ id });

我在寻找:

return this.taskRepository.updateById(id, { state, dueDate }); // returns updated task

5 个答案:

答案 0 :(得分:4)

我发现我可以使用.save方法执行此操作:

return this.taskRepository.save({
    ...task,
    state,
    dueDate
});

答案 1 :(得分:3)

尽管我希望await Table.update({}, {})返回Table,但不是。我发现只使用QueryBuilder会更容易,因为如果您不喜欢QueryBuilder 或不喜欢{{1}不需要,您可以执行以下操作:

const post = await Post.update({id}, {...input}).then(response => response.raw[0]);
return post; // returns post of type Post

但是,如果您确实想使用QueryBuilder,则建议采用以下方法。 上面的其他人提到了RepositoryTable.save()的用法,它们实际上并没有在任何地方返回原始的type,所以这种方法对我来说是无法想象的。

QueryBuilderTable.update({}, {})的示例:

@Mutation(() => PostResponse, { nullable: true })
@UseMiddleware(isAuthorized)
async updatePost(
  @Arg("id", () => Int) id: number,
  @Arg("input") input: PostInput,
  @Ctx() { req }: Context
): Promise<PostResponse | null> {

  const { userId } = req.session;
  const errors = validatePost(userId, ...input, await Post.findOne(id));

  if (errors) {
    return { errors };
  }

  const post = await Post.update({id}, {...input}).then(response => response.raw[0]);
  // OR
  const post = await getConnection()
    .createQueryBuilder()
    .update(Post)
    .set({ ...input })
    .where('id = :id and "creatorId" = :creatorId', {
      id,
      creatorId: userId,
    })
    .returning("*")
    .execute()
    .then((response) => {
      return response.raw[0];
    });

  return { post };
}

密钥正在返回response.raw[0]以恢复类型。


我将结果抽象到一个Response类中,这就是为什么我在这里返回不同的东西的原因。为清楚起见添加了

@ObjectType()
class FieldError {
  @Field()
  field!: string;
  @Field()
  message!: string;
}

@ObjectType()
export class PostResponse {
  @Field(() => [FieldError], { nullable: true })
  errors?: FieldError[];

  @Field(() => Post, { nullable: true })
  post?: Post;
}

注意:我在这里使用TypeORM和Type-GraphQL。

.returning("*")在MySQL上不起作用,请参见下面的注释。

答案 2 :(得分:2)

为了扩展sandrooco的答案,这就是我要做的事情:

const property = await await this.propertyRepository.findOne({
  where: { id }
});

return this.propertyRepository.save({
  ...property, // existing fields
  ...updatePropertyDto // updated fields
});

答案 3 :(得分:1)

一种方法是执行更新,然后根据您指定的条件进行查找

答案 4 :(得分:0)

现在可以通过TypeORM docs通过以下方式实现:

await repository.update({ firstName: "Timber" }, { firstName: "Rizzrak" });
// executes UPDATE user SET firstName = Rizzrak WHERE firstName = Timber

await repository.update(1, { firstName: "Rizzrak" });
// executes UPDATE user SET firstName = Rizzrak WHERE id = 1