【问题标题】:Relay nodeDefinition throws "Right-hand side of 'instanceof' is not callable"中继 nodeDefinition 抛出“'instanceof' 的右侧不可调用”
【发布时间】:2017-08-28 15:00:08
【问题描述】:

我正在学习 GraphQL,过去几天我刚刚开始在我的节点服务器上实现 graphql-relay。在声明我的中继节点定义时,我收到错误“'instanceof' 的右侧不可调用”,其中右侧是具有构造函数的对象。据我所知,这不是由于使用不当,还考虑到这是从文档中复制的。我不确定它正常工作时的预期结果是什么,我假设它返回 GraphQL 类型以进行工作并返回请求的数据。

var {nodeInterface, nodeField} = nodeDefinitions(
  (globalId) => {
    var {type, id} = fromGlobalId(globalId);
     console.log(type);
    if (type === 'User') {
      return db.models.user.findById(id)
   } else if (type === 'Video') {
       return db.models.video.findById(id)
    }
    else if (type === 'Producer') {
      return db.models.user.findById(id)
    }
    else if (type === 'Viewer') {
      return db.models.user.findById(id)
    }else {
      return null;
    }
  },
  (obj) => {

  console.log(obj);               // Sequelize object
  console.log(User);              // user
  console.log(User.constructor);  // valid constructor

  // This is where the error occurs
  if (obj instanceof User) {
    return UserType;
  } else if (obj instanceof Video)  {
    return VideoType;
  } else {
    return null;
  }
});

注意事项:

  • 使用 Sequelize ORM。
  • User 是 GraphQL 中的一个接口,由 Viewer、Producer 和 GeneralUser 类型实现的模式。另一方面,我的 psql 数据库有一个 User 表,这就是为什么第二个函数只检查 User 而不是这些其他类型的原因。
  • 我对用户、视频等的所有其他查询都可以正常工作,只有在通过节点 && globalId 搜索时才会中断

【问题讨论】:

    标签: graphql instanceof relayjs


    【解决方案1】:

    “具有构造函数的对象”是不可调用的。可能您需要使用这样的构造函数将该对象设为类:

    class User {
      constructor(id, name, email) {
        this.id = id;
        // etc
      }
    }
    

    【讨论】:

    • 它有一个构造函数,我将它记录到我的控制台。我已经找到了一个在未来应该稳定的解决方法。
    【解决方案2】:

    您需要从以下位置更改代码:

    ...
    
    if (obj instanceof User) {
    
    ...
    
    } else if (obj instanceof Video)  {
    
    ....
    

    到:

    ...
    
    if (obj instanceof User.Instance) {
    
    ...
    
    } else if (obj instanceof Video.Instance)  {
    
    ....
    

    【讨论】:

      猜你喜欢
      • 2017-09-16
      • 2017-01-18
      • 2019-09-17
      • 2018-01-11
      • 1970-01-01
      • 1970-01-01
      • 2020-04-05
      • 1970-01-01
      • 2023-01-31
      相关资源
      最近更新 更多