I have a database storing some videogames. Each of them has three release dates: one for Europe, another for America and a last one for Japan.
I would like to allow users of my GraphQL API to search for games according to these dates. For exemple, in order to get name and release date of games released in Europe and America but not released in Japan, we can write this query:
{
games(has_been_released: { eur: true, usa: true, jap: false }) {
data {
name
release_date
}
}
}
Therefore, if we want to fetch games released in all regions, the query will be this one:
{
games(has_been_released: { eur: true, usa: true, jap: true}) {
data {
name
release_date
}
}
}
When all booleans have the same value, I would like to simplify the query so that we could write the below instead:
{
games(has_been_released: true) {
data {
name
release_date
}
}
}
In order to do that, I've tried this type definition for field has_been_released
(with graphql-php):
<?php
$regionalizedBooleanInput = new InputObjectType([
'name' => 'RegionalizedBooleanInput',
'description' => 'An object with properties "eur", "usa" and "jap" as booleans',
'fields' => [
'eur' => ['type' => Type::boolean(), 'defaultValue' => null],
'usa' => ['type' => Type::boolean(), 'defaultValue' => null],
'jap' => ['type' => Type::boolean(), 'defaultValue' => null],
]
]);
$booleanOrRegionalizedBooleanInputType = new UnionType([
'name' => 'BooleanOrRegionalizedBooleanInput',
'description' => 'A boolean that can be different according to regions',
'types' => [
Type::boolean(),
$regionalizedBooleanInput,
],
'resolveType' => function($value) use ($regionalizedBooleanInput) {
if ($value->type === 'boolean') {
return Type::boolean();
}
return $regionalizedBooleanInput;
},
]);
But when I do that, GraphiQL throws this error:
Error: Introspection must provide object type for possibleTypes. at invariant (chrome-extension://fkkiamalmpiidkljmicmjfbieiclmeij/dist/chromeiql.js:14605:11) at getObjectType (chrome-extension://fkkiamalmpiidkljmicmjfbieiclmeij/dist/chromeiql.js:72489:80) at Array.map () at buildUnionDef (chrome-extension://fkkiamalmpiidkljmicmjfbieiclmeij/dist/chromeiql.js:72566:47) at buildType (chrome-extension://fkkiamalmpiidkljmicmjfbieiclmeij/dist/chromeiql.js:725
So I assume something is wrong with my types definition, but I don't get why. Any ideas?
tl;dr: I would like to have a GraphQL field which can accept a scalar value or an InputObject with this scalar type as fields. Is it even possible?
Thanks in advance!
GraphQL currently doesn't support polymorphic input type or Union in input . https://github.com/graphql/graphql-spec/issues/488
One solution could be all_regions to part of input schema but not mandatory
input Regions{
eur: Boolean
usa: Boolean
jpa: Boolean
all_regions: Boolean
}
{
games(has_been_released: { all_regions: true}) {
data {
name
release_date
}
}
}