Kind: Type
Custom scalar for date-time
DateTime is a custom GraphQL scalar used to represent date-time values in a consistent, API-friendly format. It’s typically serialized as an ISO-8601 string in responses and parsed/validated on input to ensure clients and services exchange timestamps reliably across the system.
Diagram
mermaidgraph LR Client[GraphQL Client] -->|Query/Mutation with DateTime| API[GraphQL API] API -->|Parse & validate| Scalar[DateTime Scalar] Scalar -->|Convert to JS Date / internal representation| Resolvers[Resolvers] Resolvers -->|Return DateTime| Scalar Scalar -->|Serialize ISO-8601 string| Client
Usage
tsimport { GraphQLScalarType, Kind } from "graphql";
// Example DateTime scalar implementation (ISO-8601)
export const DateTime = new GraphQLScalarType({
name: "DateTime",
description: "Custom scalar for date-time",
serialize(value: unknown): string {
const date = value instanceof Date ? value : new Date(String(value));
if (Number.isNaN(date.getTime())) throw new TypeError("DateTime cannot serialize invalid date");
return date.toISOString();
},
parseValue(value: unknown): Date {
const date = new Date(String(value));
if (Number.isNaN(date.getTime())) throw new TypeError("DateTime cannot parse invalid date");
return date;
},
parseLiteral(ast): Date {
if (ast.kind !== Kind.STRING) throw new TypeError("DateTime must be a string literal");
const date = new Date(ast.value);
if (Number.isNaN(date.getTime())) throw new TypeError("DateTime cannot parse invalid date");
return date;
},
});
// Example usage in schema (SDL):
// scalar DateTime
// type Event { id: ID!, startsAt: DateTime! }
// Example resolver returning a JS Date (will serialize to ISO string)
export const resolvers = {
DateTime,
Query: {
serverTime: () => new Date(),
},
Mutation: {
createEvent: (_: unknown, args: { startsAt: Date }) => ({
id: "evt_123",
startsAt: args.startsAt, // parsed by DateTime.parseValue
}),
},
};
AI Coding Instructions
- Treat
DateTimevalues as ISO-8601 strings at the GraphQL boundary; convert toDate(or your internal time type) inside resolvers/services. - Validate inputs aggressively (
Invalid Datechecks) to avoid silently accepting malformed timestamps and propagating bad data. - Be explicit about timezone behavior: prefer
toISOString()(UTC) for serialization to keep client/server consistent. - When integrating with DB/ORM layers, standardize on one representation (e.g., store as UTC, return
Dateobjects to GraphQL so the scalar can serialize). - Avoid accepting non-string literals in
parseLiteralunless you intentionally support them; mixed formats are a common source of client incompatibilities.
Referenced By
User(TYPE_OF)User(TYPE_OF)Post(TYPE_OF)Post(TYPE_OF)Post(TYPE_OF)Comment(TYPE_OF)Comment(TYPE_OF)Like(TYPE_OF)Follow(TYPE_OF)
Was this page helpful?