【问题标题】:Graphql not resolving as expectedGraphql 未按预期解决
【发布时间】:2019-01-22 21:34:20
【问题描述】:

我正在开发一个 GraqphQL-API,它通过 Mongoose 从 MongoDB 获取数据。现在我遇到的问题是 GraphQL 不使用查询来解析字段,而是使用无法工作的字段解析器,因为没有设置 ID。

类型定义:

type Query{      
  getUser(user_id: String!): User
  getGroup(group_id: String!): Group    
}
type Group {
  name: String
  scopes: [Scope]
  id: String
}

解析器:

Query: {
  getUser: (root,args,context) => {
     console.log(args);
     return getUser(args.user_id);
  },
   getGroup: (root,args,context) => {
     return getGroup(args.group_id);
   }
},
Group: {
  scopes(group){
     return getScopes(group.id);
  },
  name(group){
       return getGroupName(group.id);
  }
},

功能:

exports.getGroup = async (id) => {

const g = await Group.findOne({_id:id});
const scopes = [];
for(let index in g.scopes){
    scopes.push({id: g.scopes[index]});
}
console.log(g.name);
return{
    name: g.name,
    scopes: scopes
};
};
exports.getGroupName = async (id) => {

const g = await Group.findOne({_id:id});
console.log(id);
return g.name;
};

exports.getScopes = async (id) => {

const g = await Group.findOne({_id:id});
const scopes = [];
for(let index in g.scopes){
    scopes.push({id: g.scopes[index]});
}
return scopes;
};

查询:

 query getUserGroup{
      getGroup(group_id:"5b74c537086152554adf818e"){name}           
 }

结果:

{
"data": {
  "getGroup": {
    "name": null
  }
},
"errors": [
  {
    "message": "Cannot read property 'name' of null",
    "locations": [
      {
        "line": 3,
        "column": 5
      }
    ],
    "path": [
      "getGroup",
      "name"
    ],
    "extensions": {
      "code": "INTERNAL_SERVER_ERROR",
      "exception": {
        "stacktrace": [
          "TypeError: Cannot read property 'name' of null",
          "    at _callee2$ (/XXXX/resolver/group.js:20:14)",
          "    at tryCatch (/XXXX/node_modules/regenerator- 
          runtime/runtime.js:65:40)",
          "    at Generator.invoke [as _invoke] 
          (XXXX/node_modules/regenerator-runtime/runtime.js:303:22)",
          "    at Generator.prototype.(anonymous function) [as next] 
          (XXXXX/node_modules/regenerator-runtime/runtime.js:117:21)",
          "    at step (XXXXX/src/resolver/group.js:5:191)",
          "    at XXXX/resolver/group.js:5:361",
          "    at <anonymous>"
      ]
    }
  }
}
]
}

【问题讨论】:

  • 在 getGroup 函数中硬编码 name 值会发生什么?
  • 当我硬编码一个值例如名称时,结果是相同的:(
  • getUser 查询对你有用吗?
  • 是的,因为没有定义字段解析器
  • 当组名返回查询解析器 (getGroup) 时,为什么您有一个字段解析器?

标签: node.js graphql apollo graphql-js apollo-server


【解决方案1】:

const g = await Group.findOne({_id:id});

"TypeError: Cannot read property 'name' of null"

"path": [
  "getGroup",
  "name"
],

你能检查g是否存在吗?

【讨论】:

  • getGroup 方法中,它不是空值,但它使用名称字段的解析器,其中没有设置id,因此gnull,而不是查询解析器
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-06-06
  • 2019-07-21
  • 1970-01-01
  • 2020-07-14
  • 1970-01-01
  • 2022-01-17
相关资源
最近更新 更多