I am trying to use Apollo Client and Apollo Server to query a third party API where the data sometimes comes in the form of a single object and sometimes comes in the form of an array of objects. I'm trying to define a union in my typeDefs gql string in order to account for the data variability, but everytime I do, I receive GraphQLError: Syntax Error: Expected Name, found "[".
. I've removed most of the schema, as it is quite long. I'm assuming I can't define a union in this way, but for the life of me can't find any explanations on another way to do it. Any help would be greatly appreciated!
const { gql } = require("apollo-server");
module.exports = gql`
type Query {
getPropertyDetails(zpid: String): [PropertyDetails]
getPropertiesOverview: [PropertyOverview]
}
union RoomOrRooms = Room | [Rooms]
type Room {
level: String
dimensions: String
features: String
roomFeatures: [String]
roomArea: String
roomAreaSource: String
roomLength: String
width: String
roomDescription: String
roomWidth: String
roomLevel: String
roomLengthWidthUnits: String
roomLengthWidthSource: String
roomDimensions: String
roomAreaUnits: String
roomType: String
length: String
description: String
area: String
}
type ResoFacts {
rooms: RoomOrRooms
}
`
I don't believe you can union a type and an array of a type, just two individual types.
But you're making your life complicated. Just have your API always return an array of rooms. If the API brings back a single room, just make it into an array of length 1.
The provided answer is correct that you can't use an array as part of a union, and I also agree that you probably should just always provide an array when it's a single one. There's not really a reason NOT to do it that way, and it'll be much much simpler to consume it that way.
That being said, if you really want to make it a single or multiple, you could do that with connections, like this:
type ReseverationRoomsConnection {
nodes: [Room]
}
union RoomOrRooms = Room | ReservationRoomsConnection
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.