Assign multiple types to a field in GraphQL
Asked Answered
N

1

6

In my database the Event field was populated both dynamically with an array of strings while some were populated manually with text (No array). When I execute my query the results that were populated with just a String (not in an array) shows up as null.

Field in the schema is: Event: [String]

Is there a way in GraphQL to assign a field both [String] and String types? I tried the following but got a syntax error:

union test = [String] | String

Event: test

Note: The manually assigned ones are not in an array.

Neruda answered 20/10, 2018 at 22:39 Comment(1)
Single-item lists in GraphQL can be treated as single objects, syntactically. So [String] should work just fine for you. Something else is the problem.Lamar
G
6

From the spec:

GraphQL Unions represent an object that could be one of a list of GraphQL Object types, but provides for no guaranteed fields between those types.

Unions cannot include scalars or lists; they can only include types. That means a union is not suitable for what you're trying to accomplish. Moreover, a field can only return one scalar, type, union or interface, so there's no inherent way to return one of something or an array of that somethings.

However, you can utilize a custom scalar to create the behavior you're looking for. The apollo docs do a great job of outlining how to create and implement your own scalars, so you can take a gander there. For your particular case, however, I think there's already a scalar that would do the trick -- graphql-type-json. I believe both a string and an array of strings would be valid JSON values so they should work with that library.

On a final note, I would advise against designing your schema this way. You're effectively losing type validation for that field and introducing unnecessary ambiguity in regards to what that field will resolve to. It will make it significantly easier on any client using your API to always just return an array of strings. If your database returns a single string, just wrap it in an array before returning it in your resolver. This will prevent the client from unnecessarily having to check whether it received a string or an array.

Gilliam answered 21/10, 2018 at 0:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.