Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I specify a graphql type that takes multiple types?

I want to create a graphql type that can return either an Array of Integers or String.

I've already tried using union in the form union CustomVal = [Int] | String, but this returns an error.

The schema declaration is:

union CustomValues = [Int] | String

type Data {
    name: String
    slug: String
    selected: Boolean
    values: CustomValues
}

The error is:

node_modules/graphql/error/syntaxError.js:24
return new _GraphQLError.GraphQLError('Syntax Error: ' + description, undefined, source, [position]);
Syntax Error: Expected Name, found [
GraphQL request (81:23)
80: 
81:     union CustomValues = [Int] | String

Is this possible to do in graphql? If not, can you please suggest an alternative to do this.

I ask this as the union documentation says that Note that members of a union type need to be concrete object types; you can't create a union type out of interfaces or other unions.

Any solutions would be highly helpful.

like image 444
Deepank Avatar asked Jun 12 '18 04:06

Deepank


People also ask

When using GraphQL which defines a set of types?

GraphQL comes with a set of default scalar types out of the box: Int : A signed 32‐bit integer. Float : A signed double-precision floating-point value. String : A UTF‐8 character sequence.

Can GraphQL have multiple schemas?

Schema stitching is the idea that you can take two or more GraphQL schemas, and merge them into one endpoint that can pull data from all of them.

How do you pass two arguments in GraphQL query?

Multiple arguments can be used together in the same query. For example, you can use the where argument to filter the results and then use the order_by argument to sort them.


1 Answers

Follow this https://github.com/facebook/graphql/issues/215, Graphql does not support scaler union types currently, you can do this

union IntOrString = IntBox | StringBox

type IntBox {
  value: Int
}

type StringBox {
  value: String
}

or you can have your custom type, see this graphql, union scalar type?

like image 194
Rajat Sharma Avatar answered Oct 04 '22 01:10

Rajat Sharma