gpt4 book ai didi

graphql - Typegraphql+TypeORM : save/update an array of entities

转载 作者:行者123 更新时间:2023-12-04 15:16:42 25 4
gpt4 key购买 nike

我有一个 graphql 服务器和一个 role 表,我想在一个突变中保存多个角色。

我搜索了很多,但一无所获。

我该如何做:

mutation {
addRoles (roles: [
{
name: "role1",
description: "role 1"
},
{
name: "role2",
description: "role 2"
},
...
])
}

也就是说,如何实现addRolesupdateRoles解析器?

for 循环是唯一的选择吗?是否可以在一次数据库调用中保存所有角色?

角色模型:

@Entity("role")
@ObjectType()
export class Role extends BaseEntity {
@Field((type) => Number)
@PrimaryGeneratedColumn()
readonly id!: number;

@Field()
@Column({ length: 64 })
name!: string;

@Field({ nullable: true })
@Column({ length: 512, nullable: true })
description!: string;
}

并添加和更新解析器:

@Resolver((of) => Role)
export class RoleResolver {

@Mutation((returns) => Boolean)
async addRole(
@Arg("role") role: AddRoleInput
): Promise<Boolean> {
const roleExists = await Role.count({ name: role.name });
if (roleExists > 0)
throw new Error(`Role with name "${role.name}" already exists!`);

const newRole = Role.create(role);
await newRole.save();
return true;
}

@Mutation((returns) => Boolean)
async updateRole(
@Arg("role") role: UpdateRoleInput
): Promise<Boolean> {
const oldRole = await Role.findOneOrFail(role.id);
Object.assign(oldRole, role);
await oldRole.save();
return true;
}
}

以及AddRoleInputUpdateRoleInput


@InputType({ description: "New Role Argument" })
export class AddRoleInput implements Partial<Role> {
@Field()
name!: string;

@Field({ nullable: true })
description?: string;
}

@InputType({ description: "Update Role Argument" })
export class UpdateRoleInput implements Partial<Role> {
@Field()
id!: number;

@Field()
name!: string;

@Field({ nullable: true })
description?: string;
}

最佳答案

我通过反复试验找到了答案。如果有人遇到同样的问题,我会在这里发布:

@Resolver((of) => Role)
export class RoleResolver {

@Mutation((returns) => Boolean)
async addRoles(
@Arg("roles", type => [AddRoleInput]) roles: AddRoleInput[]
): Promise<Boolean> {

// also checks at front
const roleExists = await Role.count({
name: In(roles.map((role) => role.name)),
});
if (roleExists > 0)
throw new Error(`Role name conflict!`);

const newRoles = []
for (let i=0, i < roles.length, i++) {
const newRole = Role.create(roles[i]);
newRoles.push(newRole);
}

// this is the solution
// turns out an entity class can be used to save instances
// failed to found this in the docs though
await Role.save(newRoles);

return true;
}
...
}

如果有更好的答案,我会保持悬赏。

关于graphql - Typegraphql+TypeORM : save/update an array of entities,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64205541/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com