Introduction
GraphQL Scalars are the basic data types that represent the leaf nodes of a GraphQL query. They are the simplest form of data that can be returned from a GraphQL server. Scalars are used to define the types of fields in your GraphQL schema.
Built-in Scalar Types
GraphQL comes with several built-in scalar types:
- Int: A signed 32-bit integer.
- Float: A signed double-precision floating-point value.
- String: A UTF-8 character sequence.
- Boolean: A true or false value.
- ID: A unique identifier, often used to refetch an object or as a key for a cache.
Example Schema with Scalars
In this example:
id
is anID
scalar type.name
andemail
areString
scalar types.age
is anInt
scalar type.isActive
is aBoolean
scalar type.balance
is aFloat
scalar type.
Using Scalars in Queries
Scalars are used in both the schema definition and the queries. Here’s an example of how you might query scalar fields:
Example Query
Example Response
{ "data": { "user": { "id": "1", "name": "John Doe", "age": 30, "email": "[email protected]", "isActive": true, "balance": 100.50 } } }
Custom Scalars
While the built-in scalars cover many common use cases, sometimes you need more specific types. For example, you might need a Date
type or a URL
type. In such cases, you can define custom scalars.
Defining a Custom Scalar
To define a custom scalar, you need to:
- Define the scalar in your schema.
- Implement the scalar in your server code.
Example: Date Scalar
Schema Definition
Server Implementation (JavaScript Example)
const { GraphQLScalarType, Kind } = require('graphql'); const DateScalar = new GraphQLScalarType({ name: 'Date', description: 'Custom scalar type for dates', parseValue(value) { return new Date(value); // value from the client input variables }, serialize(value) { return value.toISOString(); // value sent to the client }, parseLiteral(ast) { if (ast.kind === Kind.STRING) { return new Date(ast.value); // value from the client query } return null; } }); const resolvers = { Date: DateScalar, Query: { event: () => ({ id: '1', name: 'GraphQL Conference', date: new Date() }) } };
Practical Exercise
Task
- Define a custom scalar type
URL
in your schema. - Implement the
URL
scalar in your server code. - Create a type
Article
with fieldsid
,title
, andurl
(using theURL
scalar). - Write a query to fetch an article by its
id
.
Solution
Schema Definition
scalar URL type Article { id: ID! title: String! url: URL! } type Query { article(id: ID!): Article }
Server Implementation (JavaScript Example)
const { GraphQLScalarType, Kind } = require('graphql'); const URLScalar = new GraphQLScalarType({ name: 'URL', description: 'Custom scalar type for URLs', parseValue(value) { try { return new URL(value); // value from the client input variables } catch (e) { throw new Error('Invalid URL'); } }, serialize(value) { return value.toString(); // value sent to the client }, parseLiteral(ast) { if (ast.kind === Kind.STRING) { try { return new URL(ast.value); // value from the client query } catch (e) { throw new Error('Invalid URL'); } } return null; } }); const resolvers = { URL: URLScalar, Query: { article: () => ({ id: '1', title: 'Introduction to GraphQL', url: new URL('https://graphql.org/') }) } };
Example Query
Example Response
{ "data": { "article": { "id": "1", "title": "Introduction to GraphQL", "url": "https://graphql.org/" } } }
Conclusion
In this section, we covered the basics of GraphQL Scalars, including built-in scalar types and how to define and use custom scalars. Scalars are fundamental to defining the types of fields in your GraphQL schema and are essential for ensuring data integrity and type safety. In the next module, we will dive deeper into more complex schema design concepts such as interfaces, unions, and enums.