Search code examples
graphqlgraphql-jsgraphql-schema

How to use Time type as scalar in a GraphQL SDL?


I have an object "business" and I'm trying to schematize it in GraphQL. Since DateTime and Time are not per default available on Graphql, i come across the following library : github.

Business.graphql:

type Business {
    businessId: ID!
    name: String!
    createdAt: Date!
    closeHour: Time
}

Unfortunately the library provides only a DateTime. How can I use only "Time" (i.e 15:00 or 09:45) for the closeHour property? Is there any other library which can help?


Solution

  • "Date" and "DateTime" can be tricky. For example, is "15:00" 3:00pm Pacific Time?

    Many (most) implementations resolve the problem by storing "datetime" as a large integer with respect to some "epoch". For example, "0" might represent "number of seconds since Jan 1, 1970".

    Perhaps you might consider storing your GraphQL "DateTime" as an ISO 8601 string, or using this module: https://www.npmjs.com/package/graphql-iso-date


    At the "schema" level (vs. JS code, as I suggested above), you might consider this:

    GraphQL Spec

    3.5 Scalars:

    Scalars ScalarTypeDefinition DescriptionoptscalarNameDirectivesConstopt Scalar types represent primitive leaf values in a GraphQL type system. GraphQL responses take the form of a hierarchical tree; the leaves on these trees are GraphQL scalars.

    All GraphQL scalars are representable as strings, though depending on the response format being used, there may be a more appropriate primitive for the given scalar type, and server should use those types when appropriate.

    GraphQL provides a number of built‐in scalars, but type systems can add additional scalars with semantic meaning. For example, a GraphQL system could define a scalar called Time which, while serialized as a string, promises to conform to ISO‐8601. When querying a field of type Time, you can then rely on the ability to parse the result with an ISO‐8601 parser and use a client‐specific primitive for time.