GraphQL:从对象构建查询参数

时间:2018-06-02 18:41:34

标签: javascript graphql graphql-js

如果我有一个对象:

{"where":{"publishedAt_lt":"2018-01-01"}}

如何将其转换为适合查询参数的字符串?

articles(where: {publishedAt_lt: "2018-01-01"})

4 个答案:

答案 0 :(得分:1)

这不是回答你的问题,但是如果你遵循最佳实践,通常不会出现你的问题:GraphQL查询应该是静态的 - 这意味着你不能从变量输入中生成它们。也许你有一个有效的用例,但我很难想象。请在评论中告诉我。

当您的客户端具有字段参数的变量输入时,您希望改为使用变量:

query getArticles($filter: ArticlesFilter) { # Please insert your input type name
  articles(where: $filter) {
    # ...
  }
}

然后,您可以在查询的变量字段中传递此输入:

let givenObject = {"where":{"publishedAt_lt":"2018-01-01"}}; // said object
fetch('/graphql', {
  method: 'POST',
  body: JSON.stringify({
    query, // put the query string from above
    variables: {
      filter: givenObject,
    },
  }),
});

现在这是普通的JS,请参考您的客户端库。我相信他们有一个关于这个的文档部分。对于react-apollo,您可以找到如何传递变量here的文档。

答案 1 :(得分:0)

这看起来像一个有趣的库,建议您将其检出:

https://www.npmjs.com/package/json-to-graphql-query

但是,基本上我们需要做的就是将对象转换为字符串,同时确保键不采用双引号并且整数不转换为字符串,因为这可能不适用于我们使用的graphql模式。

由于JSON.stringify()无法完成此操作,因此我想到了这个小功能来帮助将参数插值到我的查询中:

/**
 * Queryfy.
 *
 * Prep javascript objects for interpolation within graphql queries.
 *
 * @param {mixed} obj
 * @return template string.
 */
const queryfy = obj => {

  // Make sure we don't alter integers.
  if( typeof obj === 'number' ) {
    return obj;
  }

  // Stringify everything other than objects.
  if( typeof obj !== 'object' || Array.isArray( obj ) ) {
    return JSON.stringify( obj );
  }

  // Iterate through object keys to convert into a string
  // to be interpolated into the query.
  let props = Object.keys( obj ).map( key =>
    `${key}:${queryfy( obj[key] )}`
  ).join( ',' );

  return `{${props}}`;

}

以下是我成功使用此代码的一部分:

const dateQuery = {};

if( !! date1 ) {

  dateQuery.after = {
    year: parseInt( date1.format( 'YYYY' ) ),
    month: parseInt( date1.format( 'M' ) ),
    day: date1.format( 'D' ) - 1,
  }

}
if( !! date2 ) {

  dateQuery.before = {
    year: parseInt( date2.format( 'YYYY' ) ),
    month: parseInt( date2.format( 'M' ) ),
    day: date2.format( 'D' ) - 1,
  }

}

const query = await client.query( {
  query: gql `{
    apiResponses( where: {
      dateQuery: ${queryfy( dateQuery )}
    } ) {
      edges {
        node {
          apiResponseId
          title
          date
          json
        }
      }
    }
  }`
} );

话虽如此,我将检查提到的库,并可能会继续使用该库。

答案 2 :(得分:0)

尝试一下:

const { where } = {"where":{"publishedAt_lt":"2018-01-01"}}
articleList = articles({where}) // assume articles takes an object - equivalent to articles({where: where}) or articles({where: {publishedAt_lt: "2018-01-01"}}

答案 3 :(得分:0)

我采用了KMcAloon方法,并使其也支持数组。这样,您就可以将查询完全作为一个对象,并在最后一步将其包装==例如

mutation createPackage {
  createPackage(
    data: ${queryfy(data)}
  ) {
    name
    _id
  })
}

/**
 * Queryfy.
 *
 * Prep javascript objects for interpolation within graphql queries.
 *
 * @param {mixed} obj
 * @return template string.
 */
const queryfy = obj => {
  // Make sure we don't alter integers.
  if (typeof obj === 'number') {
    return obj;
  }

  if (Array.isArray(obj)) {
    const props = obj.map(value => `${queryfy(value)}`).join(',');
    return `[${props}]`;
  }

  if (typeof obj === 'object') {
    const props = Object.keys(obj)
      .map(key => `${key}:${queryfy(obj[key])}`)
      .join(',');
    return `{${props}}`;
  }

  return JSON.stringify(obj);
};