立即学习GraphQL,并在“映射”对象属性方面遇到一些问题。
我正在尝试映射该对象https://data.metromobilite.fr/api/ficheHoraires/json?route=SEM:C&time=1544221514650
(注意:您可以将时间戳更改为将来的时间戳,请在此处https://currentmillis.com/找到)
这是JSON格式:
{
"0": {
"arrets": [],
"trips": [],
"prevTime": 1544217780000,
"nextTime": 1544229600000
},
"1": {}
}
我的代码:
const SheetType = new GraphQLObjectType({
name: "Sheet",
fields: () => ({
arrets: { type: ArretsType },
trips: { type: TripsType },
prevTime: { type: GraphQLString },
nextTime: { type: GraphQLInt }
})
});
const TimeSheetType = new GraphQLObjectType({
name: "TimeSheet",
fields: () => ({
0: { type: SheetType },
1: { type: SheetType }
})
});
但是,我不知道如何映射对象,因为键是数字,并且不可能按数字(https://facebook.github.io/graphql/June2018/#sec-Names)映射字段。
我该怎么办?
谢谢。
答案 0 :(得分:0)
如果API始终只返回键“ 0”和“ 1”,则您可以有两个任意命名的字段,它们映射回API返回的键。
const TimeSheetType = new GraphQLObjectType({
name: "TimeSheet",
fields: () => ({
zero: {
type: SheetType,
resolve: (parent) => parent['0'],
},
one: {
type: SheetType,
resolve: (parent) => parent['1'],
},
})
})
另一方面,如果API可以返回名为“ 2”,“ 3”,“ 4”等的键,则更好的选择是更改数据结构的结构以改用数组。在这种情况下,您将完全省略TimeSheetType
,而只返回List
中的SheetType
。
// An example of how you can iterate over keys and reduce an object to an array
const convertToArray = (obj) => Object.keys(obj).reduce((arr, key) => {
arr[Number.parseInt(key, 10)] = obj[key]
return arr
}, [])
// Example query returning the array of SheetType objects
const QueryType = new GraphQLObjectType({
name: "Query",
fields: () => ({
getTimeSheets: {
type: new GraphQLList(SheetType),
resolve: async () => {
const apiResponse = await getAPIResponse()
return convertToArray(apiResponse)
},
},
})
})