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.
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
}
}
}
After creating this content type on admin dashboard, source code should look like this:
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;
},
})
);
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: [],
},
},
],
};
Now go to admin dashboard, grant permission access this enpoint to Authenticated users
3. Test it
Try to call this endpoint from Postman:
Don't hesitate to ask me if you have any question :D @huylvz
Top comments (0)