代码之家  ›  专栏  ›  技术社区  ›  hamidreza nikoonia Quoc Ly

为graphql中的参数名称(不是参数值)设置$variable

  •  1
  • hamidreza nikoonia Quoc Ly  · 技术社区  · 8 年前

    我在本项目中使用了阿波罗

    我想在ApolloClient中使用查询组件从服务器获取一些产品,我的查询模式是这样的

     products(isExisting:true) {
        id
        name
      }
    

    products(minPrice:$price)
       id
       name
     } 
    

    现在我想创建一个程序,用于在两个参数中进行选择:平面[A]内使用(isExisting)arg和平面[B]内使用(minPrice)

    我的第一个愚蠢的解决方案是创建两个不同的查询组件,是否有其他方法,例如,为这样的参数设置变量

     products($choose:$value)   
    

    我还知道graphql中的指令 https://graphql.github.io/learn/queries/#directives

    我的第二个解决方案是将javascript变量放入```,如下所示

       render() {
    
          const arg = 'minPrice';
    
              return(
                   <Query
                      variables={{ }}
                        query={gql`
    
                               query {
                                  products(${arg}:100) {
                                     id
                                     name }
    

    我检查了这个,对我来说很好,但我想知道这是一个好的更好的方法

    1 回复  |  直到 8 年前
        1
  •  1
  •   parisa    8 年前

    我认为最后一个解决方案,是采用这种方法的一个好主意,而且你们必须知道指令只适用于文件

     products(isExist:true) {
        name @include if(false/true)
     }
    

    这意味着,如果条件返回True,则获取(name)字段,如果返回False,则查询中不包含(name)字段

     products(isExist:true) {
        name @skip if(false/true)
     }
    
    
         @include(if: Boolean) Only include this field in the result if the            argument is true.
          @skip(if: Boolean) Skip this field if the argument is true.
    
    推荐文章