andres martinez
andres martinez

Reputation: 1439

Strapi: GraphQL ctx.state is undefined

I have a custom controller to replace a default querie named "groupedOrders" but when I try to test the query the response is

"message": "Cannot read property 'user' of undefined",

the code in api/grouped-order/controllers/grouped-order.js is:

module.exports = {
    byUser: async ctx => {
        const user = ctx.state.user
        const resTypeUser = await strapi.query('tipo-usuario').find({ _id: user.tipo_usuario })
        var resGroupedOrder = { error: true }
        if (resTypeUser[0].super_admin) {
            resGroupedOrder = await strapi.query('grouped-order').find()
        } else if (resTypeUser[0].cliente) {
            resGroupedOrder = await strapi.query('grouped-order').find({ users_permissions_user: user._id })
        }

        return resGroupedOrder
    }
};

and the code in api/grouped-order/config/schema.graphql.js is:

module.exports = {
  definition: ``,
  query: ``,
  type: {},
  resolver: {
    Query: {
      groupedOrders: {
        description: "Retornar todos los pedidos dependiendo el tipo de usuario",
        resolverOf: "application::grouped-order.grouped-order.byUser",
        policies: [
            'plugins::users-permissions.permissions',
        ],
        resolver: async (obj, options, ctx) => {
          return await strapi.controllers["grouped-order"].byUser(ctx);
        }
      }
    },
  },
}

the test that I try to run in http://localhost:1337/graphql is:

query groupedOrders($where:JSON){
  groupedOrders(where:$where){
    createdAt
    detail
    status
  }
}

and the HTTP HEADERS:

{ 
  "Authorization": "Bearer TOKENJWT"
}

Upvotes: 0

Views: 678

Answers (1)

andres martinez
andres martinez

Reputation: 1439

Solved, I just add this code on my controller:

if (!ctx.state && ctx.request && ctx.request.header && ctx.request.header.authorization) {
            const { id } = await strapi.plugins["users-permissions"].services.jwt.getToken(ctx);
            ctx.state.user = await strapi.plugins['users-permissions'].services.user.fetchAuthenticatedUser(id);
        }

we can add the code globally, like this: https://github.com/strapi/strapi/issues/9159#issuecomment-789484109

Upvotes: 1

Related Questions