How to add custom route for user

Viewed 3848

I have created a books content type containg books. Each book in the collection belongs to a user (user content type provided by Strapi).

I want to return list of books owned by authenticated user at /users/me/books endpoint. Where can I add this route and handler as there is /api/books directory containing books related route, controllers, etc. but not /api/users directory.

1 Answers

You can extend or override using the extensions system.

extensions/users-permissions/controllers

Just add the controller you want to extend or override as a .js file like so:

So to override the me endpoint under User.js you only need to define the method again:

'use strict';
module.exports = {
  //Override me
  async me(ctx) {
      //do your thing
  }
};

To extend, not override, means to add another endpoint, therefor you need to define it, add a route and set permissions for it. The routes.js files should be created at:

extensions/users-permissions/config/routes.json

Like so:

{
    "routes": [
    {
      "method": "GET",
      "path": "/users/me/books",
      "handler": "User.getUserBooks",
      "config": {
        "policies": [],
        "prefix": "",
        "description": "description",
        "tag": {
          "plugin": "users-permissions",
          "name": "User",
          "actionType": "find"
        }
      }
    }
}

The controller this time (same location as in beginning):

module.exports = {
    async getUserBooks(ctx) {
      //add logic
    }
}

OP correctly added:

After adding custom route and controller, one has to go to Admin Panel(log in as admin)>Roles and Permission> Users-Permission. There you can find the newly added route and have to enable it by checking it.

The originals(if you need examples) are located at:

/node_modules/strapi-plugin-users-permissions/config/routes.json
/node_modules/strapi-plugin-users-permissions/controllers/User.js

I don't think you should extend the User controller as it isn't logically correct. You are trying to GET books - you should extend the book api in the same way. From what I can tell a ContentType doesn't contain information about its creator(you're welcome to educate me if it's not true). So to tackle that you can add to your ContentType "books" a relation to User. Then I think you should extend the books api with a endpoint that returns books "belonging" to that user using the ctx received.

Also - check this question out

Comment if you need more info.

Related