Hey everyone, I am getting errors when trying to utilize hooks to create necessary rows to connect a 'user' to their newly created 'organization'. All in all, I am using PostgreSQL with Payload. Here is the hook:
export const createDefaultPrimaryAdminRole: CollectionAfterOperationHook = async ({ result, operation, req }) => {
if (operation !== "create") return result;
try {
const payload = req.payload;
const primaryAdmin: any = await payload.create({
collection: "roles",
data: {
name: "Owner",
description: "Owner role with full access to all collections.",
permissions: JSON.stringify(defaultPermissionsObject),
is_system_role: true,
created_by: req?.user?.id,
},
overrideAccess: true
});
if (primaryAdmin?.id) {
const organizationMember = await payload.create({
collection: "organization-members",
data: {
organization: result?.id,
user: req?.user?.id as string,
role: primaryAdmin?.id,
created_by: req?.user?.id,
},
overrideAccess: true
});
if (organizationMember?.id) {
// ... updates user to have org-member ID
}
}
} catch (err) {
console.error(err);
} finally {
return result;
}
}
The error is always triggered when I am creating the role and trying to apply that new role's ID to the new organization-member. It returns an ID but for some reason, the ID is invalid or not found in my database there for violating the fk constraint. Is this a timing issue within Payload and it's document creation is taking an 'optimistic approach', or am I missing something by using PostgreSQL?