问题描述
我有一个自定义控制器来替换名为groupedOrders"的默认查询;但是当我尝试测试查询时,响应是
I have a custom controller to replace a default querie named "groupedOrders"but when I try to test the query the response is
消息":无法读取未定义的属性用户"",
api/grouped-order/controllers/grouped-order.js 中的代码是:
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
}
};
api/grouped-order/config/schema.graphql.js 中的代码是:
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);
}
}
},
},
}
我尝试在 http://localhost:1337/graphql 中运行的测试是:
the test that I try to run in http://localhost:1337/graphql is:
query groupedOrders($where:JSON){
groupedOrders(where:$where){
createdAt
detail
status
}
}
和 HTTP 标头:
{
"Authorization": "Bearer TOKENJWT"
}
推荐答案
解决了,我只是在我的控制器上添加了这段代码:
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);
}
我们可以全局添加代码,像这样:https://github.com/strapi/strapi/issues/9159#issuecomment-789484109
we can add the code globally, like this: https://github.com/strapi/strapi/issues/9159#issuecomment-789484109
这篇关于Strapi:GraphQL ctx.state 未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!