Customize controllers in Strapi V4.05

System Information
  • Strapi Version:
  • Operating System:
  • Database: sqlite
  • Node Version:
  • NPM Version:
  • Yarn Version:

Hey, I’m creating a custom controller to be used on a custom route. It should return all the events for current user. But I got a 404. Your help would be appreciated. Thanks.
/src/api/event/routes/me.js

"use strict";

module.exports = {
  routes: [
    {
      method: "GET",
      path: "/events/me",
      handler: "event.me",
      config: {
        policies: [],
      },
    },
  ],
};

/src/api/event/controllers/event.js

"use strict";

/**
 *  event controller
 */

const { createCoreController } = require("@strapi/strapi").factories;

module.exports = createCoreController("api::event.event", ({ strapi }) => ({
  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
      .service("api::event.event")
      .find({ user: user.id });

    if (!data) {
      return ctx.notFound();
    }
    const sanitizedEntity = await this.sanitizeOutput(data, ctx);
    return this.transformResponse(sanitizedEntity);
  },
}));

Hi, on your route config, try setting auth:false

...
config: {
  policies: [],
  auth: false
},
...

Thank you, but it still give me a 404.

1 Like

Did you:
1). Allow the authenticated role to use the action ‘me’ in your Event content-type (you are depending on the current authorized user to fulfill the request) in settings.

2). Be sure to add ‘api’ in from of the request, for example: http://localhost:1337/api/events/me (if this url is not correct you will get a 404 error).

Otherwise, your code looks fine.

Thanks cajazzer!

I allowed the authenticated role to use “me” in the Event content-type and the request url is “http://localhost:1337/api/events/me”. But I got a 404 error.

I am not familiar with this line:

return this.transformResponse(sanitizedEntity);

I got this from the documentation.

// path: ./src/api/restaurant/controllers/restaurant.js

const { createCoreController } = require('@strapi/strapi').factories;

module.exports = createCoreController('api::restaurant.restaurant', ({ strapi }) =>  ({
  // Method 1: Creating an entirely custom action
  async exampleAction(ctx) {
    try {
      ctx.body = 'ok';
    } catch (err) {
      ctx.body = err;
    }
  },

  // Method 2: Wrapping a core action (leaves core logic in place)
  async find(ctx) {
    // some custom logic here
    ctx.query = { ...ctx.query, local: 'en' }
    
    // Calling the default core action
    const { data, meta } = await super.find(ctx);

    // some more custom logic
    meta.date = Date.now()

    return { data, meta };
  },

  // Method 3: Replacing a core action
  async findOne(ctx) {
    const { id } = ctx.params;
    const { query } = ctx;

    const entity = await strapi.service('api::restaurant.restaurant').findOne(id, query);
    const sanitizedEntity = await this.sanitizeOutput(entity, ctx);

    return this.transformResponse(sanitizedEntity);
  }
}));

I tried to test with Postman with Bearer token, got a 404 error too.

I found your problem. Naming a custom route ‘me.js’ is the problem. I created an Event content type like yours and was able to re-create your problem. I would call your route something like ‘custom-event.js’. That worked for me. I hope your database is just for testing because changing the route file broke Strapi for me.
Cheers

3 Likes

It worked!!!

Thank you so much for your help. I really appreciate it.

Awesome! :+1: