import type { Core } from "@strapi/strapi"; import type { Context } from "koa"; /** * Custom create handler for events * * When creating an event: * 1. Create the event using Strapi's default create method * 2. Automatically create an EventRelationship with relation "owner" for the creator * 3. Return the created event with populated data * * POST /events */ export default ({ strapi }: { strapi: Core.Strapi }) => async function create(ctx: Context) { const userId = ctx.state.user?.id; // Validation if (!userId) { return ctx.badRequest( "User ID is required. You must be logged in to create an event." ); } try { const groupId = ctx.request.body.data.group; // Format tags from array of strings to array of component objects const data = ctx.request.body.data; delete data.group; if (data.tags && Array.isArray(data.tags)) { data.tags = data.tags .filter((tag: any) => { // Skip if already formatted as object, or if it's null/empty if (typeof tag === "object") return true; return tag && String(tag).trim().length > 0; }) .map((tag: any) => { // Convert string tags to component format if (typeof tag === "string") { return { tag: tag.trim() }; } return tag; }); } // 1. Call the default Strapi create method const event = await strapi.entityService.create("api::event.event", { data, }); if (!event) { return ctx.internalServerError("Failed to create event"); } // 2. Create the owner relationship const contextType = groupId && groupId !== 0 ? "group" : "user"; const contextId = groupId && groupId !== 0 ? groupId : userId; const ownerRelationship = await strapi.db .query("api::event-relationship.event-relationship") .create({ data: { author: userId, event: event.id, contextType, contextId, relation: "owner", metas: { createdAt: new Date().toISOString(), }, }, }); strapi.log.info( `Event ${event.id} created by user ${userId} with owner relationship ${ownerRelationship.id}` ); if (contextType === "group") { await strapi .service("api::group.group") .addActivity( contextId, ctx.state.user?.username || `User ${userId}`, `Evènement créé : ${event.title}` ); } ctx.send({ data: event }, 201); } catch (error) { strapi.log.error("Error in create event controller:", error); return ctx.internalServerError( `Failed to create event: ${error.message}` ); } };