【问题标题】:Passing user input into GQL Queries将用户输入传递给 GQL 查询
【发布时间】:2019-01-04 22:43:07
【问题描述】:

我目前正试图弄清楚如何通过使用用户通过表单提交的文本数据作为返回结果数组的查询中的变量参数来实现搜索功能。 AssetQueryInit 查询的结果很好。 (AssetQueryInit 只是呈现硬编码查询的结果)

我是新手,如有任何帮助,将不胜感激!

GraphQL 服务器

const typeDefs = `
  type Asset {
    _id: ID
    assetName: String
    headline: String
    language: String
    sentimentNegative: Float
    sentimentNeutral: Float
    sentimentPositive: Float
    firstCreated: String


  }
  type Query {
    asset(assetName: String!): Asset
    assetAll(assetName: String!): [Asset]
  }
`;

const resolvers = {
  Query: {
    asset: (_,{assetName})=> Asset.findOne({assetName : assetName }),
    assetAll: (_,{assetName}) => Asset.find({assetName: assetName})
  }
};

const server = new GraphQLServer({ typeDefs, resolvers });

反应

const AssetAllQuery = gql`
{
    assetAll(assetName: $text){
      _id
      assetName
      headline
      firstCreated
      sentimentNegative
      sentimentPositive
      sentimentNeutral
    }
} 
`;



class App extends Component {
  assetAll = async (text) =>{
    await this.props.assetAll({
      variables:{
        assetName: text
      },
      update:(store,{data: {assetAll}}) => {
        const data = store.readQuery({query: AssetAllQuery});
        data.assetAll.unshift(assetAll);
      }
    });
  };

  render() {
        const {
            data : { loading, assetAll }
          } = this.props;
        console.log("test");
    if(loading){
      return null;
    }
    return (
      <div className="App">
      <Form submit ={this.getAllAssets}/>
      {assetAll.map(Asset => <div key={Asset._id}>{Asset.headline} | {Asset.sentimentNeutral > Asset.sentimentPositive ?  (Asset.sentimentNeutral > Asset.sentimentNegative ? "Neutral" : "Sell") : "Buy"} </div>)}
      </div>
    );
  }
};

export default compose(
  graphql(AssetAllQuery, {name: "assetAll"}),
  graphql(AssetQueryInit)
  )(App);

输出

[GraphQL error]: Message: Variable "$text" is not defined., Location: [object Object],[object Object], Path: undefined  bundle.js:837:32

[Network error]: Error: Response not successful: Received status code 400

【问题讨论】:

    标签: mongodb mongoose graphql react-apollo


    【解决方案1】:

    在查询中,您使用的任何$variables 基本上都必须“声明”为整个事物的输入参数:

    const AssetAllQuery = gql`
    AssetAll($assetName: String!) {
        assetAll(assetName: $assetName){
            ...
        }
    } 
    `;
    

    顶级操作名称并不重要; $variable 有自己声明的类型,并且必须匹配查询主体中使用的类型;当您进行查询时,variables: 的名称必须与声明的查询参数的名称相匹配。

    【讨论】:

      猜你喜欢
      • 2012-06-25
      • 2021-07-19
      • 1970-01-01
      • 1970-01-01
      • 2019-12-08
      • 1970-01-01
      • 2021-06-21
      • 2022-01-09
      • 1970-01-01
      相关资源
      最近更新 更多