Last active
May 1, 2022 04:27
-
-
Save Azerothian/dc84f009a94579b5bb43 to your computer and use it in GitHub Desktop.
Convert JS Objects to GraphQL Queries
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
// Babel 2015 - ES6 | |
// Convert a complex JS Object to GraphQL Query, should handle most use cases as of 21/01/2016 | |
const o = { | |
query: { | |
fields: { | |
complex: { | |
aliasFor: "Products", | |
processArgs: { | |
coupon: (value) => { | |
return `"${JSON.stringify(value).replace(/"/g, "\\\"")}"`; // passing json string as a argument | |
} | |
}, | |
args: { | |
coupon: { | |
name: { | |
$eq: "Test", | |
} | |
}, | |
complexCoupon: { | |
name: { | |
$eq: "Test", | |
} | |
} | |
}, | |
fields: { | |
"...productFields": null | |
}, | |
}, | |
products: { | |
aliasFor: "Products", | |
args: { | |
coupon: "coupon", | |
buildingCode: "code" | |
}, | |
fields: { | |
"...productFields": null | |
} | |
} | |
} | |
}, | |
productFields: { | |
fragment: "Product", | |
fields: { | |
id: null, | |
"... @include": { // 5.4.1.2 Fragment Spread Type Existence | |
args: { | |
if: true | |
}, | |
fields: { | |
name: null | |
}, | |
}, | |
"... on User": { // 5.4.1.2 Fragment Spread Type Existence | |
fields: { | |
name: null | |
}, | |
}, | |
name: null, | |
description: null, | |
options: { | |
fields: { | |
plan: { | |
fields: { | |
renew: null | |
}, | |
}, | |
}, | |
}, | |
} | |
} | |
} | |
export default function createGQLQuery(obj) { | |
let result = Object.keys(obj).map((k) => { | |
let query = `${k}`; | |
let element = obj[k]; | |
if (element) { | |
if (element.aliasFor) { | |
query = `${k}:${element.aliasFor}`; | |
} | |
if (element.fragment) { | |
query = `fragment ${k} on ${element.fragment}`; | |
} | |
if (element.args) { | |
let args = Object.keys(element.args).map((argKey) => { | |
let argVar = "", processed = false; | |
if (element.processArgs) { | |
if (element.processArgs[argKey]) { | |
argVar = element.processArgs[argKey](element.args[argKey]); | |
processed = true; | |
} | |
} | |
if (!processed) { | |
if (typeof element.args[argKey] === "object") { | |
argVar = JSON.stringify(element.args[argKey]).replace(/\"([^(\")"]+)\":/g, "$1:"); | |
} else { | |
argVar = `"${element.args[argKey]}"`; | |
} | |
} | |
return `${argKey}:${argVar}`; | |
}).join(); | |
query = `${query}(${args})`; | |
} | |
if (element.fields) { | |
let fields = createGQLQuery(element.fields); | |
query = `${query}${fields}`; | |
} | |
} | |
return `${query}`; | |
}).join(); | |
return `{${result}}`; | |
} | |
const query = createGQLQuery(o); | |
console.log(query); | |
document.body.innerHTML = query; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This doesn't work for nested object. This worked for me: