Search code examples
graphqlstrapi

Limit Graphql results that belongs to owner in Strapi


I am using a simple Strapi policy like below to limit the REST result that belongs to the owner only, which documented in the following link.

https://github.com/strapi/strapi/issues/624

module.exports = async (ctx, next) => {
  const { id, role } = ctx.state.user;
  if(role !== 'administrator'){
    ctx.query.owner = id;
  }
  await next();
};

Now I want to do the same for Graphql results, but it doesn't seems to work with the same code because "ctx.query" is undefined. I have tried looking at the all the request API but none of them seems to be work for Graphql query. The URL ended like 'http://localhost:1337/graphql', and 'ctx.request.query' is an empty [].

https://strapi.io/documentation/3.0.0-beta.x/guides/requests.html#api-reference


Solution

  • Here what I did to solve that problem:

    Override the GraphQl Schema in api/activity/config/schema.graphql

    module.exports = {
        definition: ``,
        query: `
            notifications(sort: String, limit: Int, start: Int, where: JSON): [Activity]
        `,
        type: {},
        resolver: {
            Query: {
                notifications: {
                    description: 'Return the auth user notifications',
                    policies: ['plugins.users-permissions.permissions'],
                    resolver: 'Activity.findNotifications'
                },
            },
        },
    };
    

    Create a new function resolver in api/activity/controllers/Activity.js

    module.exports = {
    
        findNotifications(ctx) {
    
            ctx.query = { ...ctx.query, owner: ctx.state.user.id }
    
            if (ctx.query._q) {
                return strapi.services.activity.search(ctx.query);
            }
            return strapi.services.activity.find(ctx.query);
        },
    }
    

    In the controller you got the query and add the owner id filter. Hope it helps.