【问题标题】:How to pass parameter to graphql query?如何将参数传递给graphql查询?
【发布时间】:2017-05-28 16:19:43
【问题描述】:

我正在尝试在 Meteor blaze 项目中使用 Apollo graphql。

我正在使用来自swydo:blaze-apollo 的包。 可以使用graphql查询从mongoDB获取数据。

// Using this one can get data
const LOCATION_COUNTRY_QUERY = gql`
{
    locations(location_type: "Country"){
        location_id
        name
        iso_code
    }
}
`;

Template.home.onCreated(function(){
    const country = this.gqlQuery({query: LOCATION_COUNTRY_QUERY}).get();
    console.log(country.locations); // Which will show an array list of country.
});

但是,我不想在查询中硬编码“国家/地区”。我想将字符串传递到查询中,然后使用其他 location_type 获取数据。但我找不到任何关于它的文章,而且 gql 语法只是阻止了任何参数。

谁有类似的经历,可以给点建议吗?

【问题讨论】:

    标签: meteor meteor-blaze graphql apollo


    【解决方案1】:

    您可以使用 GraphQL 变量来完成这项工作。 首先,将变量声明为您的LOCATION_COUNTRY_QUERY

    const LOCATION_COUNTRY_QUERY = gql`
    query locationCountryQuery($locationType: String!){
        locations(location_type: $locationType){
            location_id
            name
            iso_code
        }
    }
    `;
    

    现在您可以为查询提供一个新的variables 选项:

    Template.home.onCreated(function(){
        const country = this.gqlQuery({query: LOCATION_COUNTRY_QUERY, variables: {locationType: "Country"}).get();
        console.log(country.locations); // Which will show an array list of country.
    }); 
    

    【讨论】:

      猜你喜欢
      • 2017-09-27
      • 2023-01-26
      • 2018-03-08
      • 2020-12-31
      • 2018-02-16
      • 2017-05-15
      • 2017-03-08
      • 2021-06-07
      • 1970-01-01
      相关资源
      最近更新 更多