Graphql 字段在类型上不存在 [英] Graphql Field doesn't exist on type

查看:28
本文介绍了Graphql 字段在类型上不存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在浏览了 Graphql 的文档后,我开始在玩具导轨/reactJS 项目中实现它.这些项目允许用户通过设计登录,然后访问显示艺术家列表的虚拟/artist 路径.在我尝试使用来自 react 应用程序的 GraphQL 的 api 数据来获取艺术家并显示它们之前,一切似乎都正常工作.

在服务器端,我有一个 graphql_controller.rb 如:

class GraphqlController <接口控制器rescue_from Errors::Unauthorized do |exception|渲染 json: {errors: ['Unauthorized.']}, status: :unauthorized结尾定义索引结果 = Schema.execute params[:query],变量:params[:variables],上下文:上下文渲染json:结果,状态:结果['错误']?422 : 200结尾私人的定义上下文令牌,选项 = ActionController::HttpAuthentication::Token.token_and_options 请求{ip_address: request.remote_ip}结尾结尾

然后,按照我的模型逻辑,我在 graph/下使用以下文件设置了 graphql:

graph/queries/artist_query.rb

ArtistQuery = GraphQL::ObjectType.define 做名称艺术家查询"description '此架构的查询根'field :artists, types[Types::ArtistType] 做解决(->(_,_,_){艺术家.all})结尾结尾

types/artist_type.rb

Types::ArtistType = GraphQL::ObjectType.define 做命名艺术家"描述 '单个艺术家.字段 :id, !types.ID字段:名称,类型.字符串字段:描述,类型.字符串结尾

schema.rb

Schema = GraphQL::Schema.define 做查询艺术家查询结尾

在客户端,为了使事情井井有条,我使用了 3 个文件来渲染此艺术家列表:

首先,ArtistSchema.js

import { gql } from 'react-apollo';const ArtistListQuery = gql`{询问 {艺术家{ID名称描述}}}`;导出默认的艺术家列表查询;

然后,一个 Artist.js

import React, { Component } from 'react';类艺术家扩展组件{使成为() {返回 (<tr><td>{this.props.index + 1}</td><td>{this.props.data.name}</td><td>{this.props.data.description} min</td></tr>);}}导出默认艺术家;

最后,将这两个组合在一个更大的布局中:Artists.jsx:

import React, { Component } from 'react';从'react-apollo'导入{graphql};从'./Artist'导入艺术家;从'./ArtistSchema'导入艺术家列表查询;类艺术家扩展组件{使成为() {如果(this.props.data.loading){返回(<p>加载</p>)} 别的 {控制台日志(this.props.data)const ArtistsItems = this.props.data.artists.map((data,i) => {return (<Artist key={i} index={i} data={data}></Artist>);});返回 (<div><h1>艺术家</h1><table className="table table-striped table"><头><tr><th>#</th><th>姓名</th><第>描述</tr></thead>{ 艺术家物品 }</tbody>

);}}}导出默认 graphql(artistListQuery)(Artists);

执行这段代码时会发生什么:

在服务器端(对于未格式化的输出很抱歉,但它在控制台中显示如下):

 GraphqlController#index 处理为 */*18:49:46 api.1 |参数:{"query"=>"{
 query {
 Artist {
 id
 name
 description
 __typename
 }
 __typename
 }
}
", "operationName"=>nil, "graphql"=>{"query"=>"{
 query {
 Artist {
 id
 name
 description
 __typename
 }
 __typename
 }
}
", "operationName"=>nil}}

出现以下错误:

在 36 毫秒内完成 422 个不可处理的实体(视图:0.2 毫秒 | ActiveRecord:0.0 毫秒)

在客户端,如果我监视 Network > Response for graphql,我(当然)会收到 422 错误代码和以下错误消息:

{"errors":[{"message":"字段 'query' 不存在于类型 'ArtistQuery'","locations":[{"line":2,"column":3}],"fields":["query","query"]}]}

我认为我的查询没有正确完成.我一直在尝试各种查询格式(来自文档或要点示例),但我无法找到一种正确的方法来取回我的艺术家数据.

我做错了什么?

解决方案

我不认为这是这个特殊情况的问题,但我收到了这个错误,结果是由于一个简单的语法错误.查询属性需要采用驼峰格式,而不是 under_score 格式.也许这会帮助像我一样搜索此错误的其他人.

After skimming through the docs of Graphql I've started to implement it on a toy rails/reactJS project. The projects allows an user to sign in through devise then access a dummy /artist route that displays a list of artists. Everything seems to work fine until I try to consume api data with GraphQL from the react app to get artists and display them.

On the server side, I have a graphql_controller.rb such as:

class GraphqlController < ApiController
  rescue_from Errors::Unauthorized do |exception|
    render json: {errors: ['Unauthorized.']}, status: :unauthorized
  end

  def index
    result = Schema.execute params[:query], variables: params[:variables], context: context
    render json: result, status: result['errors'] ? 422 : 200
  end

private

  def context
    token, options = ActionController::HttpAuthentication::Token.token_and_options request
    {
      ip_address: request.remote_ip
    }
  end
end

Then, following to my model logic, I have set up graphql under graph/ with the following files:

graph/queries/artist_query.rb

ArtistQuery = GraphQL::ObjectType.define do
  name 'ArtistQuery'
  description 'The query root for this schema'

  field :artists, types[Types::ArtistType] do
    resolve(->(_, _, _) {
      Artist.all
    })
  end
end

types/artist_type.rb

Types::ArtistType = GraphQL::ObjectType.define do
  name 'Artist'
  description 'A single artist.'

  field :id, !types.ID
  field :name, types.String
  field :description, types.String
end

schema.rb

Schema = GraphQL::Schema.define do
  query ArtistQuery
end

On the client side, for the sake of keeping things organized, I use 3 files to render this artist list:

First, ArtistSchema.js

import { gql } from 'react-apollo';

const artistListQuery = gql`
    {
        query {
            artists {
                id
                name
                description     
            }
        }
    }
`;

export default artistListQuery;

Then, an Artist.js

import React, { Component } from 'react';

class Artist extends Component {
    render() {
        return (
            <tr>
                <td>{this.props.index + 1}</td>
                <td>{this.props.data.name}</td>
                <td>{this.props.data.description} min</td>
            </tr>
        );
    }
}

export default Artist;

And finally, wrapping these two together in a larger layout: Artists.jsx:

import React, { Component } from 'react';
import {graphql} from 'react-apollo';
import Artist from './Artist';
import artistListQuery from './ArtistSchema';

class Artists extends Component {
    render() {
        if(this.props.data.loading) {
            return (<p>Loading</p>)
        } else {

            console.log(this.props.data)
            const ArtistsItems = this.props.data.artists.map((data,i) => {
                return (<Artist key={i} index={i} data={data}></Artist>);
            });
            return (
                <div>
                    <h1>Artists</h1>
                    <table className="table table-striped table">
                        <thead>
                        <tr>
                            <th>#</th>
                            <th>Name</th>
                            <th>Description</th>
                        </tr>
                        </thead>
                        <tbody>
                        { ArtistsItems }
                        </tbody>
                    </table>
                </div>
            );
        }

    }
}

export default graphql(artistListQuery)(Artists);

What happens when this code is executed:

On server-side (sorry for the unformatted output, but it displays like this in console):

Processing by GraphqlController#index as */*
18:49:46 api.1  |   Parameters: {"query"=>"{
  query {
    artists {
      id
      name
      description
      __typename
    }
    __typename
  }
}
", "operationName"=>nil, "graphql"=>{"query"=>"{
  query {
    artists {
      id
      name
      description
      __typename
    }
    __typename
  }
}
", "operationName"=>nil}}

Followed by the error:

Completed 422 Unprocessable Entity in 36ms (Views: 0.2ms | ActiveRecord: 0.0ms)

On the client side, if I monitor Network > Response for graphql, I (of course) receive a 422 error code and the following error message:

{"errors":[{"message":"Field 'query' doesn't exist on type 'ArtistQuery'","locations":[{"line":2,"column":3}],"fields":["query","query"]}]}

I assume my query is not done correctly. I have been trying various queries formats (from docs or gists examples) but I cannot end finding a correct way to get back my artist data.

What am I doing wrong?

解决方案

I don't think this is the issue for this particular case, but I was getting this error and it turned out to be due to a simple syntax error. Query attributes need to be in camelCase format, not under_score format. Maybe this will help someone else that lands here when searching for this error like I did.

这篇关于Graphql 字段在类型上不存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆