【问题标题】:How to check an array with regular expression in GraphQL如何在 GraphQL 中使用正则表达式检查数组
【发布时间】:2019-06-08 20:00:08
【问题描述】:

我需要检查数组中某些元素是否存在

我有一个这样的数组

ar = ['一','二','三']

我想知道如何单独检查下面正则表达式代码中的元素,而不是通过我的数组映射并检查它们是否存在于 graphQL 中的“/something/”。

similar : allCockpitHello (filter: {Association : {value : {regex: "\/something/" }}} limit:2){
      nodes{
        Name{
          value
        }
}

【问题讨论】:

    标签: reactjs graphql


    【解决方案1】:

    您需要将正则表达式字符串作为解析器使用的输入参数,GraphQL 不会为您执行过滤器,您需要根据您的输入在解析器中执行/调用该逻辑。

    根据您的示例,您可以在架构和解析器上使用类似的内容:

    type Node {
       name: String!
    }
    
    type NodeQueries {
       nodes (filterRegEx :String): [Node]!
    }
    

    一旦你在解析器上输入了字符串,过滤机制的实现就取决于你了。

    const resolvers = {
    ...
    NodeQueries: {
        nodes: (parent, params) => {
          const {filterRegEx} = params; // regex input string
    
          const ar = ['one','two','three'];
    
          // Create a RegExp based on the input, 
          // Compare the with the elements in ar and store the result...
          // You might end up with ... res = ['one', 'three'];
          // Now map the result to match your schema:
    
          return _.map(res, name => ({name}) ); // to end up with [{name: 'one'}, {name: 'three'}]
        }
    }
    ...
    

    }

    【讨论】:

      【解决方案2】:

      GraphQL 不是灵丹妙药 - 它只是一种查询语言,它将您的需求“传输”到引擎(本地客户端、远程服务器……),所有必要的处理都会在引擎中进行。

      在这种情况下,您可能需要将数组和表达式作为变量传递给服务器(解析器)。如果处理成本高,结果(相似关系)应该已经定义、缓存、预处理等。

      如果数据集很小,您可以完全在客户端执行此操作 - 遍历数组(使用 graphql 获取)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-08-07
        • 1970-01-01
        • 2011-03-27
        • 1970-01-01
        • 2022-12-05
        • 1970-01-01
        • 2023-03-22
        相关资源
        最近更新 更多