Skip to content

Instantly share code, notes, and snippets.

@alapini
Created August 24, 2018 13:41
Show Gist options
  • Select an option

  • Save alapini/b3050307b3148ef9b3fcf1ca0f37ce5b to your computer and use it in GitHub Desktop.

Select an option

Save alapini/b3050307b3148ef9b3fcf1ca0f37ce5b to your computer and use it in GitHub Desktop.
Javascript Object to Graphql Query
// Source : https://gist.github.com/Azerothian/dc84f009a94579b5bb43#gistcomment-2002977
function isObject(avar) {
// cosntructor.name tested for `function Animal(){}; var a = new Animal(); isObject(a);` will return true otherwise as it is [Object object]
return Object.prototype.toString.call(avar) === '[object Object]' && avar.constructor.name === 'Object';
}
function createGqlQuery(obj) {
let shape = [];
for (let [key, val] of Object.entries(obj))
shape.push(isObject(val) ? `${key} { ${createGqlQuery(val)} }` : key);
return shape.join(' ');
}
const SHAPE = {
id: 'string.isRequired',
name: 'string.isRequired',
address: 'string.isRequired',
creator: {
displayname: 'string.isRequired',
id: 'string.isRequired'
},
owner: {
displayname: 'string.isRequired',
id: 'string.isRequired'
},
level0: {
level1: {
level2: {
levelLast: 'bool'
}
}
}
}
console.log(createGqlQuery(SHAPE)); // outputs "id name address creator { displayname id } owner { displayname id } level0 { level1 { level2 { levelLast } } }"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment