本文介绍了GraphQL:从对象构建查询参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个对象:

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

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

How can I convert it to a string suitable for query arguments?

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

推荐答案

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

This looks like an interesting library, I would suggest checking it out:

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

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

But basically all we need to do is to convert the object to a string while ensuring the keys do not adopt double quotes and integers are not converted into strings, as that might not play well with the graphql schemas we're working with.

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

Since JSON.stringify() won't accomplish this, I came up with this little function to help with interpolating arguments into my queries:

/**
 * 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}}`;

}

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

Here is a reduced portion of my code where I am using this successfully:

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
        }
      }
    }
  }`
} );

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

That being said, I am going to check out the library mentioned and probably use that moving forward.

这篇关于GraphQL:从对象构建查询参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-23 05:24