By creating a custom controller in Strapi, convenient access to a Context object is granted. This allows for retrieving the current user and utilizing the user's data as needed:
module.exports = createCoreController("api::event.event", ({ strapi }) => ({
//Retrieve logged in users
async me(ctx) {
const user = ctx.state.user;
if (!user) {
return ctx.badRequest(null, [
{ messages: [{ id: "No authorization header was found" }] },
]);
}
const data = await strapi.entityService.findMany("api::event.event", {
filters: {
user: user.id,
},
});
if (!data) {
return ctx.notFound();
}
const sanitizedEntity = await sanitize.contentAPI.output(data);
return { data: sanitizedEntity };
},
}));
On the other hand, when attempting to extend the Core services by creating a custom service, the context object does not seem to be available as with the controllers:
module.exports = createCoreService("api::event.event", ({ strapi }) => ({
//https://docs.strapi.io/developer-docs/latest/development/backend-customization/services.html#extending-core-services
async create(params) {
console.log("inside event.js - create");
console.log("params", params);
console.log("params to save", params);
// some logic here
const result = await super.create(params);
// some more logic
return result;
},
async update(entityId, params) {
params.data.user = entityId;
// some logic here
const result = await super.update(entityId, params);
// some more logic
return result;
},
}));
If it is possible, I would like to have access to the context object in custom services in order to retrieve user info, obtain the user id, and assign that id as the owner or creator of the entry.
Is this achievable and how can it be done?