乐闻世界logo
搜索文章和话题

How do you define custom scalar types in GraphQL?

1个答案

1

Defining custom scalar types in GraphQL is a highly useful feature that enables you to define more specific data types in your API, thereby ensuring the validity and consistency of data. Custom scalar types are commonly used for handling data in specific formats, such as dates, times, or latitude and longitude.

Step 1: Defining Scalar Types

First, you need to declare your custom scalar type within the GraphQL schema definition. For example, if you want to define a scalar type for dates, you can start as follows:

graphql
scalar Date

This declaration creates a custom scalar type named Date, but it lacks specific implementation logic.

Step 2: Implementing the Scalar Type

Within the GraphQL server implementation, you must define the specific behavior of this scalar type, including how to parse and serialize data of this type. This is typically done in the GraphQL server configuration. For example, when using JavaScript with Apollo Server, you can implement it as follows:

javascript
const { GraphQLScalarType } = require('graphql'); const { Kind } = require('graphql/language'); const dateScalar = new GraphQLScalarType({ name: 'Date', description: 'Date custom scalar type', serialize(value) { // Convert Date object to string return value.toISOString(); // assuming value is a JavaScript Date object }, parseValue(value) { // Convert string to Date object return new Date(value); }, parseLiteral(ast) { if (ast.kind === Kind.STRING) { return new Date(ast.value); } return null; // invalid input returns null } });

In this example, we define how to serialize internal Date objects into ISO strings and how to parse ISO strings back into Date objects. We also handle date strings provided directly in queries.

Step 3: Using Custom Scalar Types

Once you have defined and configured the custom scalar type on the server, you can use it within your GraphQL schema just like built-in types. For example, you can define a field that returns a Date type:

graphql
type Query { today: Date }

In the server's resolver, you can return the current date as follows:

javascript
const resolvers = { Query: { today: () => new Date() } };

Summary

By defining custom scalar types, you can enhance the expressiveness and data validation capabilities of your GraphQL schema. This is highly beneficial for building robust and type-safe APIs. Ensure that when implementing custom scalar types, you thoroughly handle all possible data conversions and error scenarios to guarantee the availability and stability of your API.

2024年7月21日 19:40 回复

你的答案