【问题标题】:how to escape variables for graphql query如何为graphql查询转义变量
【发布时间】:2019-02-15 03:52:20
【问题描述】:

我使用 Angular 6 用 Apollo 编写我的网站,以便与 graphpl 服务器交互。在将它们添加到我的gql 查询之前,我希望能够对从客户端获取的参数进行转义。

这是我的服务文件:

import { Injectable } from '@angular/core';
import {Apollo} from 'apollo-angular';
import gql from 'graphql-tag';

@Injectable({
  providedIn: 'root'
})
export class ProductService {

  constructor(private apollo: Apollo) { }

  searchForProduct(productName: string) {
    return this.apollo.watchQuery<any>({
    query: gql`{products_by_p_name_search(lang_id:1,query:"${productName}")
    {category_id,price,category_name,id,name,desc,quantity,year_manufacture,image_file}}`
    });
  }

}

正如您在此处看到的,函数searchForProduct 正在接收我添加到gql 查询中的productName 参数。如何正确转义它,以便查询包含特殊字符时不会被破坏?

谢谢!

【问题讨论】:

    标签: angular escaping graphql apollo


    【解决方案1】:

    在 GraphQL 中,您的查询应该是静态的,这意味着查询字符串不应在运行时更改(我希望有更多的最佳实践分享,对此感到抱歉)。为了实现这一点,GraphQL 附带了对变量的支持。变量在查询字符串中定义,然后在不同的属性中发送到服务器。

    查询示例:

    query getProducts($productName: String!) {
      products_by_p_name_search(lang_id:1,query: $productName) {
        category_id
        price
        category_name
        id
        name
        desc
        quantity
        year_manufacture
        image_file
      }
    }
    

    然后将变量添加到您的客户端调用中:

    return this.apollo.watchQuery<any>({
      query, //...
      variables: { productName }
    });
    

    这样就不需要转义 GraphQL (!)。

    【讨论】:

      【解决方案2】:

      你也可以在 js es6 中使用模板字面量。

      例如:

      const singleProduct = product.id;
      
        const queryProduct = `{
          product(id:
            "${singleProduct}") {
                variants(first: 15) {
                  edges {
                    node {
                      id,
                      title
                    }
                  }
                }
          }
        }`;
      

      【讨论】:

      • 这不安全,我正在使用它,但它不起作用,当收到特殊字符时查询会改变
      猜你喜欢
      • 2018-03-02
      • 1970-01-01
      • 2019-05-17
      • 2023-03-12
      • 2021-03-04
      • 2017-05-15
      • 2020-04-03
      • 2019-04-11
      • 2020-07-09
      相关资源
      最近更新 更多