When I create a custom controller in Strapi I get convenient access to a Context object where I can get the current user and use that user's data as I wish:
module.exports = createCoreController("api::event.event", ({ strapi }) => ({
//Get 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 };
},
}));
However when I create a custom service by trying to extend the Core services, I don't seem to have the context object as above:
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 possible I would like to access the context object because I would like to access the user info and get user id and add that id as the owner or creator of that entry.
Is it possible and how does one do that???