如何将2点符号字符串合并到GraphQL查询字符串 [英] How can I merge 2 dot notation strings to a GraphQL query string

查看:203
本文介绍了如何将2点符号字符串合并到GraphQL查询字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试仅使用javascript(可以是ES6/打字稿)将2个点表示法字符串合并到GrahQL查询中.

I'm trying to merge 2 dot notation strings into a GrahQL query with only javascript (it can be ES6/typescript).

例如,假设我有一个字符串数组

For example, let say that I have an array of strings

[
    'firstName', 
    'lastName', 
    'billing.address.street', 
    'billing.address.zip', 
    'shipping.address.street', 
    'shipping.address.zip'
]

预期的查询字符串输出为(空格不重要)

The expected query string output would be (white spaces are not important)

firstName, lastName, shipping{address{street, zip}}, billing{address{street, zip }}

我可以将点表示法按1转换为查询字符串,但是如何将所有这些符号合并在一起?我有一个使用street.name并输出street { name }的函数.所以这个功能可以做到

I can convert 1 by 1 the dot notation to a query string, but how do I merge all of that together? I got a function that take street.name and output street { name }. So this function would do it

convertToString(inputString) {
    let result = '';

    if (inputString.indexOf('.') === -1) {
      result = inputString;
    } else {
      const inputArray = inputString.split('.');
      for (let i = inputArray.length - 1; i >= 0; i--) {
        if (i === 0) {
          result = inputArray[i] + result;
        } else {
          result = '{' + inputArray[i] + result + '}';
        }
      }
    }
    return result;
}

console.log(convertToString('address.street')); // address { street }

但是接下来,我将如何遍历所有字符串并仅获得1个将相同属性组合为一组的GraphQL查询字符串.主要问题是如何合并2个点表示法字符串而不丢失任何内容且没有重复项(此时,我可以得到此address { name } address { zip },但是当它在GraphQL服务器上运行时,仅保留后者,因此仅保留zip出现在结果中.

But then how would I loop through all strings and get only 1 GraphQL query string that combines the same properties into a group. The main issue is how do I merge the 2 dot notation strings without losing anything and without having duplicates (at this point, I can get this address { name } address { zip } but when this runs on the GraphQL server, only the latter is kept and so only the zip shows up in the result.

我尝试创建代表该结构的临时对象,但效果并不理想.

I tried creating temporary object that represent the structure, but that didn't work out so good.

推荐答案

修订后的答案

根据您修改后的问题和要求,以下是修改后的答案.这将从嵌套的点表示法递归地构建一个对象,然后利用JSON.stringify来构建查询字符串(通过一些字符串操作);

Based on your revised question and requirements, here's a revised answer. This will recursively build an object from nested dot notations, and then leverage JSON.stringify to build the query string (with some string manipulations);

function buildQuery(...args) {
  const set = (o = {}, a) => {
    const k = a.shift();
    o[k] = a.length ? set(o[k], a) : null;
    return o;
  }
  
  const o = args.reduce((o, a) => set(o, a.split('.')), {});
  
  return JSON.stringify(o)
    .replace(/\"|\:|null/g, '')
    .replace(/^\{/, '')
    .replace(/\}$/, '');
}

const query = buildQuery(
  'firstName', 
  'lastName', 
  'billing.address.street', 
  'billing.address.zip', 
  'shipping.address.street', 
  'shipping.address.zip'
);

console.log(query);

原始答案

我建议先将各个点符号字符串转换为对象,然后再将该对象转换为字符串.

I would suggest converting the individual dot notation strings into an object first, and then converting the object to a string.

function buildQuery(...args) {
    let q = {};

    args.forEach((arg) => {
        const [ o, a ] = arg.split('.');
        q[o] = q[o] || [];
        if (a) q[o] = q[o].concat(a);
    });

    return Object.keys(q).map((k) => {
        return q[k].length ? `${k} \{ ${q[k].join(', ')} \}` : k;
    }).join(', ');
}

const query = buildQuery('person.name', 'person.email', 'street.name', 'street.zip');
console.log(query);
// "person { name, email }, street { name, zip }"

这篇关于如何将2点符号字符串合并到GraphQL查询字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆