Unlocking the Power of Strapi v4: Leveraging Context within a Service

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?

Answer №1

Service methods function similarly to regular functions, allowing you to specify parameters when creating a Service method. In this example, the Service method is named customServiceMethod. Simply call the customServiceMethod within your controller and pass the ctx (context) to it. Within the controller file:

/**
 * vehicle-post controller
 */

import { factories } from "@strapi/strapi";

export default factories.createCoreController(
  "api::vehicle-post.vehicle-post",
  {
    async create(ctx) {
      return await strapi
                   .services["api::vehicle-post.vehicle-post"]
                   .customServiceMethod(ctx);

    },
  }
);

then in the Service file:

module.exports = ({ strapi }: { strapi: Strapi }) => ({
  async customServiceMethod(context) {
  // ctx will be accessible here using context parameter we defined.
  console.log(context);
  }
});

Answer №2

For those Strapi users who come across this post, there is now a different approach to achieving the same result:

module.exports = createCoreService("api::event.event", ({ strapi }) => ({
 myFunction() {
    const context = strapi.requestContext.get();
    // Perform necessary actions
  },
}));

More details can be found in the documentation:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Learn how to create a scrolling div using a combination of CSS and JavaScript with absolute and relative

After relying solely on "pre-made" components like Mui or TailWind, I decided to create a component using only CSS and maybe JavaScript. However, I encountered some difficulties when attempting to position a div inside an image using relative and absolute ...

The Material-ui Drawer element is failing to display its internal items

In my current project, I am building a practice e-commerce application utilizing React.js, @material-ui/core/Drawer, and Redux. I've encountered an issue where manually rendering items to the Drawer works fine, but utilizing a handleAddToCart function ...

Exploring different pages in an Ionic and AngularJS mobile application

I am brand new to the world of Ionic and AngularJS. I have just started working on a simple project but have hit a roadblock. My goal is, To create a login page and a register page. When a user clicks the register button on the login page, they should be ...

What is the best way to obtain a direct file link from a server URL using JavaScript?

After acquiring a file located at /home/johndoe/index.html, I am utilizing a tool like XAMPP to host, with the folder /home being hosted on localhost. The variables in play are as follows: $server_addr = "localhost"; $server_root = "/home"; $file_dir = " ...

Reduce the size of a container element without using jquery

In my Angular application, I have structured the header as follows: -- Header -- -- Sub header -- -- Search Box -- -- Create and Search Button -- -- Scroll Div -- HTML: <h1> Header </h1> <h3> Sub header </h3> <div class="s ...

Navigating with parameters in Next.js using the `router.push` method

Is there a way to maintain parameters and anchors while redirecting from one page to another using router.push or similar in Next.js? For example: site.com/blog/12#comments?param=somevalue&param2=anothervalue => site.com/blog/some-blog-post#comme ...

Two DataTables on a Single Page - Odd Initialization in the Second One

My page contains two dataTable elements and I've created a method as shown below: function ToDataTable() { $(".dataTable").css("width", "100%"); $(".dataTable").each(function () { var $that = $(this); /* Start of custom ...

Set a NodeJS variable equal to a specific value based on an array within a MongoDB document

Within my MongoDB collection, I currently have the following documents: > db.mycol.find() { "_id" : ObjectId("5ec6506171ae442136aa97d2"), "uname" : "mail1", "port" : 1000, "abc" : "test1" } { "_id" : ObjectId("5ec659e6c0b1cc11370d8378"), "uname" : "mai ...

Placing the IconButton within an AppBar Component using React-JS

Trying to position two IconButtons within a Toolbar, one on the right side and the other on the left side. However, both are ending up on the right side. Here's my code: <AppBar position="fixed" > <Toolbar> <Ic ...

The issue causing "ReferenceError: fetch is not defined" is causing the test to fail

There seems to be an issue with my project where 'node-fetch' is installed, but the rest of the files are not importing it and the tests are not failing import { IQuery } from 'models/IQuery.interface'; import { NextApiRequest, NextApiR ...

How are the actions in react redux able to utilize dispatch and getState methods?

Could you please explain how the actions.js in the reddit example of the react redux docs is able to access the dispatch and getState functions without importing them explicitly? I was under the assumption that every method needed to be imported in each ...

Unexpected issue on AngularJS application

Encountering issues with incorporating a controller into my page - each time I add it to a DOM element, an error is thrown. Here's the structure of my HTML page: <html data-ng-app="sportsStore"> <head> <title>Sports Sto ...

Shopping with CommerceJS just got easier with the convenience of using PayPal

Hey there! I'm currently working on an exciting e-commerce project, creating a new store from scratch. However, I've hit a roadblock when it comes to setting up the checkout process. I'm using CommerceJS and integrating PayPal transactions w ...

useEffect not triggering when the orientation is updated

I am experimenting with adjusting the height of a container specifically for mobile landscape mode. While using the developer tools to simulate changing the orientation of a mobile device, I noticed that this adjustment only works on the initial rendering. ...

Determining the visible dimensions of an iframe

Is there a way to determine the visual size inside an iframe using JavaScript or jQuery? In this scenario, only a portion of the iframe is displayed. The iframe itself has dimensions of 300x300, but it is being limited by a div to 300x100. <div style= ...

What is the best way to save numerous records using the saveRecord function in nlapi methods?

After customizing the default promotion form, I implemented a feature where clicking on a specific promotion triggers dynamic elements to be displayed using jQuery. Since the fields or records for this requirement haven't been created yet, multiple re ...

In Angular, the exclusion of a name attribute in a textarea element does not automatically generate an instance

I came across this jade template for creating a modal dialog in Angular Material. Unfortunately, I couldn't convert it to HTML because the jade site was not working. md-dialog(aria-label='Reject', ng-cloak='') form(name="rejecti ...

Display HTML instead of text in print mode

Hello, I need help with printing HTML code, specifically an iframe. When I try to add my HTML iframe code, it only prints as plain text. I want to be able to see the actual iframe with its content displayed. Thank you. <script> const messages = [&apo ...

Highcharts real-time data not refreshing following modification of PHP variable

Currently, I have a live updating highchart implemented on a webpage named index.html. This highchart calls a PHP script called datatest.php to parse a CSV file, convert the data into JSON format, and then add it as a new point on the chart: $.ajax({ ...

utilizing the .on method for dynamically inserted elements

I have a code snippet that triggers an AJAX request to another script and adds new <li> elements every time the "more" button is clicked. The code I am using is as follows: $(function(){ $('.more').on("click",function(){ var ID = $(th ...