如何在 GraphQL SDL 中使用时间类型作为标量?

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

我有一个对象 "business",我正在尝试将其图解化为 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
}

遗憾的是,该库仅提供日期时间。我如何才能仅使用 "Time"(即 15:00 或 09:45)作为 closeHour 属性?还有其他图书馆可以提供帮助吗?

"Date" 和 "DateTime" 可能很棘手。例如,“15:00”是 3:00pm 太平洋时间吗?

许多(大多数)实现通过将 "datetime" 存储为相对于某些 "epoch" 的大整数来解决问题。例如,“0”可能代表 "number of seconds since Jan 1, 1970".

也许您可以考虑将 GraphQL "DateTime" 存储为 ISO 8601 字符串,或使用此模块:https://www.npmjs.com/package/graphql-iso-date


在 "schema" 级别(相对于 JS 代码,正如我上面所建议的),您可能会考虑:

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.