node.js - 抽象类型 Node 必须在运行时解析为字段 Root.node 的对象类型,值为\"\",收到\"null\"。”

标签 node.js reactjs relayjs

我正在使用 React 和 Relay 实现搜索功能。 下面是我的 schema.js

var { nodeInterface, nodeField } = nodeDefinitions(
  (globalId) => {
    var { type, id } = fromGlobalId(globalId);
    if (type === 'User') {
      return getUser(id);
    }else if (type === 'Post') {
      return getPost(id);
    }else if (type === 'Setting') {
      return getSetting(id);
    }
    return null;
  },
  (obj) => {
    if (obj instanceof User) {
      return userType;
    }else if (obj instanceof Post) {
      return postType;
    }else if (obj instanceof Setting) {
      return settingType;
    }
    return null;
  }
);

var postType = new GraphQLObjectType({
  name: 'Post',
  fields: {
    _id: {
      type: new GraphQLNonNull(GraphQLID)
    },
    createdAt: {
      type: GraphQLString
    },
    id: globalIdField('Post'),
    title: {
      type: GraphQLString
    },
    color: {
      type: GraphQLString
    },
    userId: globalIdField('User'),
    username: {
      type: GraphQLString,
      resolve: (post) => getUserById(post.userId),
    },
    content: {
      type: GraphQLString
    },
    images: {
      type: postImageType,
      description: "Post's main image links"
    }
  },
  interfaces: [nodeInterface]
});
const {
  connectionType: postConnection,
} = connectionDefinitions({name: 'Post', nodeType: postType});

var settingType = new GraphQLObjectType({
  name: 'Setting',
  fields: {
    _id: {
      type: new GraphQLNonNull(GraphQLID)
    },
    id: globalIdField('Setting'),
    amount: {
      type: GraphQLString
    },
    all_posts: {
      type: postConnection,
      args: {
       ...connectionArgs,
        query: {type: GraphQLString}
      },
      resolve: (rootValue, args) => connectionFromPromisedArray(
        getAllPosts(rootValue, args),
        args
      ),
    },
  },
  interfaces: [nodeInterface]
});

var Root = new GraphQLObjectType({
  name: 'Root',
  fields: () => ({
    node: nodeField,
    setting: {
      type: settingType,
      args: {
         ...connectionArgs,
          currency: {type: GraphQLString}
        },
      resolve: (rootValue, args) => {
       return getSetting(args.currency).then(function(data){
        return data[0];
       }).then(null,function(err){
        return err;
       });
      }
    },
  })
});

下面是我的database.js

export function getAllPosts(params,args) {
  let findTitle = {};
  let findContent = {};
  if (args.query) {
    findTitle.title = new RegExp(args.query, 'i');
    findContent.content = new RegExp(args.query, 'i');
  }
  console.log("getAllPosts",args)
  return new Promise((resolve, reject) => {
      Post.find({$or: [findTitle,findContent]}).sort({createdAt: 'descending'}).exec({}, function(err, posts) {
        if (err) {
          resolve({})
        } else {
          resolve(posts)
        }
      });
  })
}

现在我想通过 $query 变量获取所有帖子 所以鉴于我是这样写的

import React, { Component } from 'react';
import Relay from 'react-relay';

class BlogList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      query: '',
    };
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit(){
    this.props.relay.setVariables({query: this.state.query});
  }
  render() {
    return (

        <div className="input-group col-md-12">
            <input type="text" onChange={this.handleChange.bind(this,"query")} value={this.state.query} name="query" placeholder="Enter Title or content"/><br/>

            <span className="input-group-btn">
                <button type="button" onClick={this.handleSubmit} className="btn btn-info btn-lg">
                    <i className="glyphicon glyphicon-search"></i>
                </button>
            </span>
        </div>
    )
  }
};

export default Relay.createContainer(BlogList, {
  initialVariables: {
    query: ''
  },
  fragments: {
    viewer: () => Relay.QL`
      fragment on Setting {
        id,
        all_posts(first: 10000000,query: $query) {
          edges {
            node {
              id,
              _id,
              title,
              content,
              createdAt,
              username,
              color,
              images{
                full
              }
            }
          }
        }
      }
    `,
  },
});

在我的 route

const SettingQueries = {
 viewer: () => Relay.QL`query{
  setting(currency: "USD")
 }`,
}
export default [{
  path: '/',
  component: App,
  queries: UserQueries,PostQueries,SettingQueries,
  indexRoute: {
    component: IndexBody,
  },
  childRoutes: [ 
  ,{
    path: 'settings',
    component: Setting,
    queries: SettingQueries,
  }]
}]

事情正在/graphql 作为 Graphql UI

但是当我从网站上搜索时,它会生成响应错误

{
  "data": {
    "node": null
  },
  "errors": [
    {
      "message": "Abstract type Node must resolve to an Object type at runtime for field Root.node with value \"\",received \"null\".",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ]
    }
  ]
}

因为我的网络浏览器正在发送如下请求 enter image description here

请告诉我我错过了什么? 另外,如果我需要添加一些额外的信息,请告诉我。

最佳答案

问题可能出在您的 nodeDefinitions() 函数中。第一个回调,也称为 idFetcher 必须返回单个对象。但是,我在你的定义中看到你返回了一个集合

var { nodeInterface, nodeField } = nodeDefinitions(
  (globalId) => {
    var { type, id } = fromGlobalId(globalId);
    ...
    }else if (type === 'Post') {
      return getPosts(); // this should be getPost(id)
    }
);

这就是为什么您的下一个回调(称为 typeResolver)失败并返回 null 的原因。

var { nodeInterface, nodeField } = nodeDefinitions(
  ...
  (obj) => {
    ...
    // here you get Promise/Collection instead of single Post instance, therefore condition failed
    }else if (obj instanceof Post) {
      return postType;
    }
    return null;
  }
);

关于node.js - 抽象类型 Node 必须在运行时解析为字段 Root.node 的对象类型,值为\"\",收到\"null\"。”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39166305/

相关文章:

node.js - 在 Node.JS 中使用 Passport 注册(注册)

javascript - Node.js Cookie 不起作用

javascript - react native 图像选择器 : Cannot read property 'showImagePicker' of undefined

javascript - 使用相对路径而不是 API 服务器进行中继突变

Graphql + 中继 graphql-relay-js 依赖

javascript - 当没有服务器可用于处理请求时,Node.js 需要更好地理解 http.request 操作

javascript - 安装express.js应用程序Node.js时出错

javascript - NextJS - 在一页上进行多次获取的动态路由

css - 如何删除按钮点击的焦点?

reactjs - 在 graphql/relay 中维护有序列表