Date, Time and DateTime scalar types for our GraphQL implementation
Most GraphQL APIs need a way to represent dates, times or timestamps of some sort. Since there is no native date type in GraphQL, people have to resort to rolling their own. To reduce the boilerplate required, this library provides a few basic scalar types that should cover most situations.
- PHP >= 7.1
- digiaonline/graphql
Installation the library using Composer:
composer require digiaonline/graphql-datetime-scalar
When wiring up your executable schema, simply pass in the types you need:
$executableSchema = buildSchema($schemaDefinition, [
'Query' => QueryResolver::class,
'Mutation' => MutationResolver::class,
], [
'types' => [
new DateScalarType(),
new TimeScalarType(),
new DateTimeScalarType(),
],
]);
While it's not strictly necessary it might be a good idea to also mention in your schema that these types exist:
scalar Date
scalar Time
scalar DateTime
You can specify the format by passing a format string to the constructor:
$dateType = new DateScalarType('j.n.Y'); // 31.12.2018
$timeType = new TimeScalarType('H:i'); // 14:35
$dateTimeType = new DateTimeScalarType('U'); // 1537361927
Like the built-in scalar types, if a value cannot be serialized or parsed correctly into a \DateTimeInterface
,
a \Digia\GraphQL\Error\InvalidTypeException
will be thrown.
MIT