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

Top comments (0)