使用axios将regex传递给graphQL查询

hk8txs48  于 2023-05-19  发布在  iOS
关注(0)|答案(1)|浏览(77)

我有一个graphQL的变化,我正在运行使用axios内部的forEach循环。我传递的值之一是作为字符串的正则表达式规则,但当我运行函数时,当我传递像^(http|https)\:\/\/[a-zA-Z0-9\u00C0-\u017F\-\.]+\.[a-zA-Z0-9\u00C0-\u017F\/\.\_\-]+?$这样的值时,我得到以下错误

[
  {
    message: 'Parse error on "\\"" (error) at [13, 32]',
    locations: [ [Object] ]
  }
]

[
  {
    message: 'Parse error on "^" (error) at [13, 34]',
    locations: [ [Object] ]
  }
]

[
  {
    message: 'Parse error on "[" (LBRACKET) at [13, 34]',
    locations: [ [Object] ]
  }
]

我的代码:

const createMut = (id, res) => `
    mutation {
        createField(input: {
            id: "${id}",
            label: "${res.label}",
            custom_validation: "${res.custom_validation}",
            }) {
            table_field {
              id
              label
            }
        }
    }
`;

const myFunc = (id, result) => {
    result.data.forEach(d => {
        axiosFunc({ query: create_fields(id, d) }).then((response) => response);
    });
}

结果中的d.custom_validation被设置为类似^(http|https)\:\/\/[a-zA-Z0-9\u00C0-\u017F\-\.]+\.[a-zA-Z0-9\u00C0-\u017F\/\.\_\-]+?$^[^\s]+(\s+[^\s]+)*$的值。但是当我调用我的函数时,我得到了上面提到的错误。如何将regex值发送到graphQL mutation?

8yparm6h

8yparm6h1#

使用查询variables,而不是尝试将变量直接注入查询:

const query = "mutation myMutation($id: ID!, $label: String, $custom_validation: String) {
  createField(input: {
    id: $id,
    label: $label,
    custom_validation: $custom_validation,
  }) {
    table_field {
      id
      label
    }
  }
}";

const myFunc = (id, result) => {
  result.data.forEach(({ label, custom_validation }) => {
    const variables = { id, label, custom_validation };
    axiosFunc({ query, variables }).then((response) => response);
  });
}

如果custom_validation是一个javascript正则表达式对象而不是字符串,那么你需要将它转换为字符串。

const variables = { id, label, custom_validation: custom_validation.toString() };

相关问题