Treating responses as unions
In addition to the previous methods, another approach is to treat our response as a union. Unions in GraphQL provide us with the ability to return one of multiple possible types. This is particularly advantageous because it enables us to easily identify whether the response contains only the errors
field or only the posts
field.
Additionally, GraphQL servers include the __typename
property on every returned object, which allows the consumer of the schema to accurately determine the type of the returned object.
In the following schema, we will introduce a union
type that will be able to represent both successful responses and responses that indicate errors:
type PostResponse{ posts: [Post!]! } enum ErrorVariant{ NOT_FOUND FORBIDDEN } type PostError{ message: String! variant: ErrorVariant } type ErrorResponse{ errors: [PostError!]! } union ResponseUnion = PostResponse | ErrorResponse...