【问题标题】:Converting GraphiQL queries to JSON将 GraphiQL 查询转换为 JSON
【发布时间】:2018-07-09 23:18:16
【问题描述】:
使用GraphQLHub,我可以对 Hacker News 上排名前三的新闻项目运行此查询:
{
hn {
topStories(limit: 3) {
title
url
timeISO
by {
id
}
}
}
}
如何将此查询导出(或转换)为 JSON?有没有可以做到这一点的 npm 包?
我看到有 graphql-to-json,但看起来您需要将 .js 文件传递到其中,而不是像上面那样的原始查询。
【问题讨论】:
标签:
javascript
json
node.js
graphql
graphiql
【解决方案1】:
有很多方法可以做到这一点,但一个简单的实现是使用 JS 对象来映射查询,然后使用 JSON.stringify() 进行序列化
如果您可以将上述查询作为字符串访问,那么您就可以按照我的意思进行操作。 AFAIK,如果查询在 JS 环境中不是字符串,而不是像 GraphiQL 这样的 IDE,那么它就会爆炸。
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))