There are so many ways to do this but a simple implementation would be to use a JS Object to map the queries and then serialize using JSON.stringify()
If you can access the above query as a string then you can do what I'm saying. AFAIK, a query would blow up if it weren't a string once in a JS environment and not an IDE like GraphiQL.
let QueryStore = {}
const getHNTopStoriesQuery = `
query getHNTopStories {
hn {
topStories(limit: 3) {
title
url
timeISO
by {
id
}
}
}
}
`
const addQuery = (queryToAdd, queries) => {
let key = queryToAdd.trim().split(' ')[1]
let queryEntry = {}
queryEntry[key] = queryToAdd
return Object.assign({}, queries, queryEntry)
}
const queryToGraphiQLQueryString = query => {
let lines = query.trim().split('\n')
let queryLines =lines.slice(1, -1).map(line => line.trim())
return encodeURIComponent(`{${queryLines.join(' ')}}`)
}
// Add Query to Store
QueryStore = addQuery(getHNTopStoriesQuery, QueryStore)
// Get a GraphiQL URI query string of a Query
let qs = queryToGraphiQLQueryString(QueryStore['getHNTopStories'])
console.log(qs)
// Print a prettified JSON of the QueryStore
console.log(JSON.stringify(QueryStore, null, 2))