Created
August 24, 2018 13:41
-
-
Save alapini/b3050307b3148ef9b3fcf1ca0f37ce5b to your computer and use it in GitHub Desktop.
Javascript Object to Graphql Query
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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