From 561a9142234ee976c7bfc0a91f5fdcd4e8875c03 Mon Sep 17 00:00:00 2001 From: Jordan Eldredge Date: Fri, 29 Dec 2023 21:48:06 -0800 Subject: [PATCH] Document serialization/deserialization of custom scalars --- website/docs/04-docblock-tags/08-scalars.mdx | 45 ++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/website/docs/04-docblock-tags/08-scalars.mdx b/website/docs/04-docblock-tags/08-scalars.mdx index 37945b19..d010b7dc 100644 --- a/website/docs/04-docblock-tags/08-scalars.mdx +++ b/website/docs/04-docblock-tags/08-scalars.mdx @@ -32,3 +32,48 @@ class Math { } } ``` + +## Serialization and Parsing of Custom Scalars + +Grats does not ([yet](https://github.com/captbaritone/grats/issues/66)) support a first-class way to define serialization and parsing logic for custom scalars. However, you can do this manually by modifying the schema after it is generated. + +For example if you had a `Date` type in your schema: + +```ts title="scalars.ts" +/** @gqlScalar Date */ +export type GqlDate = Date; +``` + +To define a custom `serialize/parseValue/parseLiteral` transform for this type, which serialized the data as a Unix timestamp, you could do the following: + +```ts title="server.ts" +import { getSchema} from "./schema"; // Generated by Grats +import { GqlDate } from "./scalars" + +const schema = getSchema(); + +const date = schema.getType("Date") as GraphQLScalarType; + +date.serialize = (value) => { + if (!(value instanceof Date)) { + throw new Error("Date.serialize: value is not a Date object"); + } + return value.getTime(); +}; +date.parseValue = (value) => { + if (typeof value !== "number") { + throw new Error("Date.parseValue: value is not a number"); + } + return new Date(value); +}; +date.parseLiteral = (ast) => { + if (!(ast.kind === "IntValue" || ast.kind === "StringValue")) { + throw new Error( + "Date.parseLiteral: ast.kind is not IntValue or StringValue", + ); + } + return new Date(Number(ast.value)); +}; + +// ... Continue on, using the schema to create a GraphQL server +```