DEV Community

Lê Vũ Huy
Lê Vũ Huy

Posted on

Extend core controller in Strapi v4

Let's assume that you have a content type named Notification, it store all the notification shows in Notification Screen. And you want to create an API to get only notification belongs to current user. Here is how to achieve this.

Image description

This content type has some columns:

// src/api/notification/content-types/notification/schema.json
{
  "kind": "collectionType",
  "collectionName": "notifications",
  "info": {
    "singularName": "notification",
    "pluralName": "notifications",
    "displayName": "Notification"
  },
  "options": {
    "draftAndPublish": false
  },
  "pluginOptions": {},
  "attributes": {
    "content": {
      "type": "text",
      "required": true
    },
    "userId": {
      "type": "integer",
      "required": true
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

After creating this content type on admin dashboard, source code should look like this:

Image description

Now you want to create an API to get only notification belongs to current user. You do not need to create a new API using npx strapi generate, just extend the generated controller.

1. Extend the core controller

//src/api/notification/controllers/notification.js

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

module.exports = createCoreController(
  'api::notification.notification',
  ({ strapi }) => ({
    async findMy(ctx) {
      const entries = await strapi
        .service('api::notification.notification')
        .find({
          filters: {
            userId: ctx.state.user.id,
          },
          sort: {
            createdAt: 'desc',
          },
        });
      ctx.body = entries;
    },
  })
);

Enter fullscreen mode Exit fullscreen mode

2. Extend core router

Create a file name my-notification.js in src/api/notification/routes/

// src/api/notification/routes/my-notification.js
module.exports = {
  routes: [
    {
      method: 'GET',
      path: '/notifications/my',
      handler: 'notification.findMy',
      config: {
        policies: [],
        middlewares: [],
      },
    },
  ],
};
Enter fullscreen mode Exit fullscreen mode

Now go to admin dashboard, grant permission access this enpoint to Authenticated users

Image description

3. Test it

Try to call this endpoint from Postman:

Image description

Don't hesitate to ask me if you have any question :D @huylvz

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay