originally posted on StepZen
Introduction
You see scalar types everywhere you look in GraphQL. Take this type definition for example:
type Tracking {
origin: String!
destination: String
weight_lbs: Int
}
Here, String
and Int
are two of GraphQL's built-in scalar types. We'll talk about what that means and how you can add your own scalars to your GraphQL schemas.
Definition
Here's how GraphQL.org defines scalar types:
A GraphQL object type has a name and fields, but at some point those fields have to resolve to some concrete data. That's where the scalar types come in: they represent the leaves of the query.
So, assuming that we are familiar with GraphQL queries, what are these leaves? In Graph Theory, we can structure our query in terms of a graph. Let's look at a graph for the query we defined above:
The nodes of the Breed
query tree are its leaves. That is, they are nodes with vertex degree 1. Vertex degrees are the number of edges (in this illustration, the arrows) connected to a vertex. These leaves will resolve to a scalar type, which can be one of GraphQL's built in scalar types or a custom type defined in the schema.
GraphQL's Scalar Types
GraphQL has its own set of scalar types that you don't have to initiate.
- Int: A signed 32‐bit integer.
- Float: A signed double-precision floating-point value.
- String: A UTF‐8 character sequence.
- Boolean: true or false.
- ID: The ID scalar type represents a unique identifier, often used to refetch an object or as the key for a cache. The ID type is serialized in the same way as a String; however, defining it as an ID signifies that it is not intended to be human‐readable.
But what if you want to use a scalar that's not on the list, like DateTime
, you can create your own scalar type-- or, just use one of StepZen's if it fits your needs.
StepZen's Scalar Types
StepZen 'builds in' Date
, DateTime
& JSON
scalar types so you can use them without having to implement your own (goodbye, extensive resolver logic!).
So, using a DateTime
scalar in a StepZen GraphQL API is as simple as adding it to your schema:
type Tracking {
origin: String!
destination: String
weight_lbs: Int
dateDelivered: DateTime
}
So a query like:
query MyQuery {
deliveryByOrigin(origin: "London") {
destination
origin
weight_lbs
dateDelivered
}
returns your data for dateDelivered
:
"data": {
"deliveryByOrigin": {
"destination": "Cairo",
"origin": "London",
"weight_lbs": 12,
"dateDelivered": "02-10-2020"
}
Conclusion
If you'd like to learn more about GraphQL and/or StepZen, head on over to our blog for a deep dive, or take a look at our docs.