1
votes

Using the GraphQLHub I can run this query for the top three news items on Hacker News:

{
  hn {
    topStories(limit: 3) {
      title
      url
      timeISO
      by {
        id
      }
    }
  }
}

How do I export (or convert) this query to JSON? Is there an npm package that'll do this?

I see that there's graphql-to-json but it looks like you need to pass a .js file into this, not a raw query like the one above.

1

1 Answers

0
votes

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))