Skip to content

Commit

Permalink
Document serialization/deserialization of custom scalars
Browse files Browse the repository at this point in the history
  • Loading branch information
captbaritone committed Dec 30, 2023
1 parent 03b2347 commit 561a914
Showing 1 changed file with 45 additions and 0 deletions.
45 changes: 45 additions & 0 deletions website/docs/04-docblock-tags/08-scalars.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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<GqlDate, number>;

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
```

0 comments on commit 561a914

Please sign in to comment.