I have a hook attached to my users collection on
afterChange, but whenever I edit a user I get this error:
POST /zelmin/collections/users/7 200 in 384ms
Failed to create system event: APIError: The collection with slug system-events can't be found. Create Operation.
at createLocal (webpack-internal:///(rsc)/./node_modules/.pnpm/payload@3.20.0_graphql@16.10.0_monaco-editor@0.52.2_react-dom@19.0.0-rc-65a56d0e-The collection
system-eventsis created! I can see it in the payload admin and also the table is created!
Here's my hook — Did I miss something? 😦
import { SystemEvent, SystemEventResourceType } from '@/types/shared';
import payload, { CollectionAfterChangeHook } from 'payload';
export const createSystemEventHook: CollectionAfterChangeHook = async ({
req,
doc,
operation,
previousDoc,
collection,
}) => {
// We don't run the hook logic if:
// There is no user authenticated performing the action
// Whenever the collection belong to "system-events" which will create an infinite loop
// Whenever the collection belong to "payload-*" which are internal system collections
if (
!req.user ||
collection.slug === 'system-events' ||
collection.slug.startsWith('payload-')
)
return doc;
try {
await payload.create({
collection: 'system-events',
data: {
userId: req.user.id,
event: operation === 'create' ? 'created' : 'updated',
resourceType: collection.slug as SystemEventResourceType,
resourceId: doc.id,
changes: undefined,
timestamp: new Date().toISOString(),
} satisfies SystemEvent,
});
return doc;
} catch (error) {
console.error('Failed to create system event:', error);
return doc;
}
};Any hint would be very much appreciated! Thank you!
if you happen to have a biit of time to have a look to this, it would be super nice! Thank you! ^^
Hey
@459393101006635038,
No worries, I see the issue here.
import payload, { CollectionAfterChangeHook } from 'payload';You cannot import
payloadin this way.
In your hook, you're giving a payload instance already. It's passed within the
reqobject.
Try this:
await req.payload.create({
collection: 'system-events',
data: {
userId: req.user.id,
event: operation === 'create' ? 'created' : 'updated',
resourceType: collection.slug as SystemEventResourceType,
resourceId: doc.id,
changes: undefined,
timestamp: new Date().toISOString(),
} satisfies SystemEvent,
req,
});ohhh I see! that worked perfectly fine! Thanks a lot
@654031862146007055❤️
My pleasure!
Star
Discord
online
Get dedicated engineering support directly from the Payload team.