Created
March 31, 2021 16:10
-
-
Save risenW/5589f6fe9b5581eb43750c91a3903ec6 to your computer and use it in GitHub Desktop.
Create graphql mutation from JSON object
This file contains 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
/** | |
I have an object like: | |
[ | |
{ | |
"id": "447c4dc3-0119-4836-afb0790ec9", | |
"name": "Food Pantry", | |
"organization_id": "0aeec5af-2490-40ca-acdab1d27", | |
"status": "Open" | |
}, | |
{ | |
"id": "447c4dc3-0119-4836-a8790ec9", | |
"name": "Food Drive", | |
"organization_id": "0aeec5af-2490-40ca-caaa7", | |
"status": "close" | |
} | |
] | |
and I want gql like so i can save to my db: | |
mutation { | |
CreateService( | |
id: "447c4dc3-0119-4836-afb0-6452c8790ec9" | |
name: "Food Pantry" | |
organization_id: "0aeec5af-2490-40ca-aca9-caaaadab1d27" | |
status: "Open" | |
){ | |
id | |
} | |
} | |
**/ | |
const { request, gql } = require('graphql-request') | |
const services = require("./data/services.json") | |
async function save() { | |
for (let i = 0; i < services.length; i++) { | |
const service = services[i]; | |
let temp1 = JSON.stringify(service) | |
temp1 = temp1.replace("{", "") | |
temp1 = temp1.replace("}", "") | |
let splits = temp1.split(",") | |
splits = splits.map((sp) => { | |
let t1 = sp.split("\":")[0].toString().replace(/"/g, '') | |
let t2 = sp.split("\":")[1] | |
return `${t1}:${t2}` | |
}) | |
splits = splits.join("\n") | |
let query = ` | |
mutation { | |
CreateService( | |
${splits} | |
){ | |
id | |
} | |
} | |
` | |
try { | |
const response = await request('https://a-grap-endpoint/graphql', query) | |
console.log(`Created ${i}: ${services.length}`); | |
} catch (error) { | |
console.log("An error occured"); | |
} | |
} | |
} | |
save() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment