我有一个不返回嵌套对象的typeDefs
我想用嵌套查询来查询拥有者和文档的公寓,但是它返回null。
该文件引用了各自的数据文件。
const apartments = require('./data/apartment.json');
const person = require('./data/person.json');
const document = require('./data/document.json');
公寓查询正确返回,但是嵌套信息(所有者和相应文档)返回null
query {
apartments{
id
code
owner{
id
name
document{
name
type
}
}
}
const typeDefs = gql`
type Query {
apartments(
id:ID
code: String
description: String
createdAt: String
updatedAt: String
): [Apartment]
person:[Person]
}
type Apartment {
id: ID
code: String
description: String
owner:[Person]
createdAt: String
updatedAt: String
}
type Person {
id: ID
name: String
document: [Document]
createdAt: String
updatedAt: String
}
type Document {
id: ID
name: String
type: String
number: String
createdAt: String
updatedAt: String
}
`
这是解析器
const resolvers = {
Query: {
apartments: () => {
return apartments;
},
person: () => {
return person;
},
document: () => {
return document;
}
}
}
任何人都可以帮助检索嵌套数据吗?
答案 0 :(得分:0)
我缺少解析器,所以我将该字段更新为人员并更新了解析器
people(parent) {
return people.filter(person => person.apartmentId === parent.apartmentId);
}
这是新模式
// Schema definition
const typeDefs = gql`
# A Block has a blockName and Apartments
type Block {
blockName: String!
blockCode: String!
apartments: [Apartment!]
}
# A Apartment has a apartmentId and people
type Apartment {
apartmentId: String!
people: [Person!]
}
# People has a name
type Person {
personName: String!
}
# Queries can fetch a list of libraries
type Query {
blocks: [Block]
}
`;
现在解析器映射如下:
// Resolver map
const resolvers = {
Query: {
blocks() {
// Return our hardcoded array of blocks
return blocks;
}
},
Block: {
apartments(parent) {
// Filter the hardcoded array of blocks to only include the respective apartment in the blockName
return apartments.filter(apartment => apartment.blockName === parent.blockName);
}
},
Apartment: {
// filter all the people that live at the same apartment
people(parent) {
return people.filter(person => person.apartmentId === parent.apartmentId);
}
}
};
,嵌套查询如下所示:
query GetPeopleByBlockAndApartment {
blocks {
blockCode
blockName
apartments {
apartmentId
people {
personName
}
}
}
}
非常感谢所有尝试提供帮助的人。