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 }}
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 }
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.