aha*_*cse 6 javascript json node.js graphql
我正在使用 Nodejs 调用一个报告 API,它给我一个 JSON 响应。可以使用不同的 ID(在本例中为不同的报告 ID)调用 api。例如:
https://report.domain.io/report/1
https://report.domain.io/report/2
Run Code Online (Sandbox Code Playgroud)
等等。由于id在不同的时间不同,它会给我不同的反应。属性名称会有所不同。所以我不能在 GraphQLObjectType 中映射它。例如,如果 JSON 响应如下:
[
{
"modelbrand": "Sony",
"modelcode": "F3111",
"avg_free_storage": 225401514
},
{
"modelbrand": "Sony",
"modelcode": "F3111",
"avg_free_storage": 224547840
}
]
Run Code Online (Sandbox Code Playgroud)
然后我可以用 GraphQL 映射它,如下所示:
Report() {
return new graphql.GraphQLObjectType({
name: "Report",
description: "This represents report",
fields: () => ({
"modelbrand": {type: graphql.GraphQLString},
"modelcode": {type: graphql.GraphQLString},
"avg_free_storage": {type: graphql.GraphQLString}
})
});
}
Run Code Online (Sandbox Code Playgroud)
因为我知道属性是固定的。但是,如果属性名称如 modelbrand、modelcode 更改为其他内容(显然不同的报告会有所不同),那么我无法在 GraphQLObjectType 中映射它。在这种情况下,我需要另一种类型(应该是 JSON 类型)来映射这些响应。不幸的是,它不能用作 GraphQL 的原始类型。我没有找到任何自定义/标量类型或节点库来解决这个问题。堆栈溢出有一个解决方案,但似乎不起作用。
我能得到一个解决方案吗?一个 Nodejs 示例将不胜感激。谢谢。
请参考这个graphql-type-json。这可以用作自定义标量 json 类型。
在模式文件中
scalar JSON
type User {
id: ID!
userDetails: JSON
}
type Query {
getUser(id: ID!): User
}Run Code Online (Sandbox Code Playgroud)
在解析器文件中
import GraphQLJSON from 'graphql-type-json';
import {User} from './connectors';
const resolvers = {
Query: getUser(_, args) {
return User.find({
where: args
});
},
JSON: {
__serialize(value) {
return GraphQLJSON.parseValue(value);
}
}
}Run Code Online (Sandbox Code Playgroud)
这可能会帮助你
| 归档时间: |
|
| 查看次数: |
3281 次 |
| 最近记录: |