0.11.8 : add create event
This commit is contained in:
62
src/api/event/controllers/create.ts
Normal file
62
src/api/event/controllers/create.ts
Normal file
@@ -0,0 +1,62 @@
|
||||
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 {
|
||||
// 1. Call the default Strapi create method
|
||||
const event = await strapi.entityService.create("api::event.event", {
|
||||
data: ctx.request.body.data,
|
||||
});
|
||||
|
||||
if (!event) {
|
||||
return ctx.internalServerError("Failed to create event");
|
||||
}
|
||||
|
||||
// 2. Create the owner relationship
|
||||
const ownerRelationship = await strapi.db
|
||||
.query("api::event-relationship.event-relationship")
|
||||
.create({
|
||||
data: {
|
||||
author: userId,
|
||||
event: event.id,
|
||||
contextType: "user",
|
||||
contextId: userId,
|
||||
relation: "owner",
|
||||
metas: {
|
||||
createdAt: new Date().toISOString(),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
strapi.log.info(
|
||||
`Event ${event.id} created by user ${userId} with owner relationship ${ownerRelationship.id}`
|
||||
);
|
||||
|
||||
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}`
|
||||
);
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user