我对Next.js和Prisma都是相当陌生的。我正在开发一个管理市议会的应用程序,因此,该应用程序的管理员可以创建用户和角色,并将角色分配给用户(即市议会员工)。
每个用户可以接收多个角色,并且这些角色可以更新,这就是说,管理员可以根据需要删除或分配更多的角色给用户。
在我的数据库模式中,我有表Customer
(也称为user,因为user是postgresql中的保留名称)、表Role
和表Customer_role
,它们表示用户和他的角色之间的关系n:m。
使用prisma更新用户角色的最佳方式是什么?现在我就是这么做的:
const updateUser = async (req: NextApiRequest, res: NextApiResponse) => {
const {
query: { id },
body: { name, email, roles },
} = req as { query: { [key: string]: string }; body: any };
try {
await prisma.customer.update({
where: { id },
data: { name, email },
});
await updateUserRoles(id, roles);
const response = await prisma.customer.findUnique({
where: { id: id },
include: {
customer_roles: {
select: {
role: {
select: {
id: true,
name: true,
},
},
},
},
},
});
res.status(200).json(response);
} catch (error) {
res.status(400).json((error as Error).message);
}
};
const updateUserRoles = async (userID: string, roles: { id: string }[]) => {
try {
await prisma.customer_role.deleteMany({
where: {
customer_id: userID,
},
});
roles.map(async (role: { id: string }) => {
await prisma.customer_role.create({
data: {
customer_id: userID,
role_id: role.id,
},
});
});
} catch (error) {
throw new Error(error);
}
};
最初,我收到一组我想要分配给用户的角色,但是当我想要更新它们时,我删除了所有当前用户角色,并再次分配它们。这会生成一个bug,因为本应返回现在已更新的用户及其新角色的响应对象没有等待函数updateUserRoles
,并将用户角色作为空数组返回。只有当我刷新页面并再次获得用户时,此错误才会得到修复。这是我的prisma模式以及。
model role {
id String @id @default(uuid())
@db.Uuid
name String @db.VarChar(255)
polls permission
news permission
events permission
work_orders permission
pharmacies permission
points_of_interest permission
subscription_events permission
customer_roles customer_role[]
created_at DateTime @default(now()) @db.Timestamptz(6)
updated_at DateTime? @default(now()) @db.Timestamptz(6)
@@index([name], name: "idx_role_name")
}
model customer_role {
id String @id @default(uuid()) @db.Uuid
customer_id String @db.Uuid
role_id String @unique @db.Uuid
customer customer @relation(fields: [customer_id], references: [id], onDelete: Cascade)
role role @relation(fields: [role_id], references: [id])
}
model customer {
id String @id @default(uuid()) @db.Uuid
name String @db.VarChar(255)
email String @unique @db.VarChar(255)
external_uuid String? @unique @db.Uuid
password String? @db.VarChar(255)
created_at DateTime @default(now()) @db.Timestamptz(6)
updated_at DateTime? @default(now()) @db.Timestamptz(6)
work_order_user work_order_user?
customer_roles customer_role[]
@@index([name], name: "idx_customer_name")
@@index([external_uuid], name: "idx_customer_external_uuid")
}
发布于 2021-09-05 21:08:35
您看不到更新角色的原因是因为您在updateUserRoles
函数下的map
中使用了async
。这将异步运行,您将不会得到所需的响应,因为它将在后台运行。
更好的方法是使用upsert
const updateUserRoles = async (userID: string, roles: { id: string }[]) => {
try {
await prisma.$transaction(
roles.map((role) =>
prisma.customer_role.upsert({
where: { id: role.id },
create: { customer_id: userId, role_id: role.id },
update: {},
})
)
)
} catch (error) {
throw new Error(error);
}
}
https://stackoverflow.com/questions/69048517
复制相似问题