Custom Scalar Type in Apollo GraphQL — Simplified
How to create a custom date scalar in Apollo GraphQL
Intro
Out of the box, GraphQL offers us some default scalar types to work with. These include Int
, Float
, String
, Boolean
, and ID
. In most cases, these are enough for us to work with to build out most applications.
There may come a time where you want to work with custom scalars — for example, working with dates. For most projects, you could get away with storing date values as a String
. But if you would like to make your application a little more robust, you can implement a custom date scalar. That is exactly what I am going to show you how to do in this article.
Prerequisites
Although not required, I recommend that you have a solid foundation in Node.js, some knowledge of GraphQL and Apollo GraphQL, so you can easily follow along with this tutorial.
- Solid foundation in Node.js
- Some knowledge of GraphQL
- Some knowledge of Apollo GraphQL
Project setup
We will take an existing project and add a custom date scalar to it. I have provided starter code for this tutorial if you wish to follow along. You can find the source code from my github link below.
Start by cloning the repository in your working directory.
git clone https://github.com/kluu1/custom-graphql-scalar.git
Next, change into the project directory, install dependencies, and start the application.
cd custom-graphql-scalar
npm install
npm run dev
Inspecting our application
This is a simple application with one query and one mutation.
orders
—query to retrieve ordersaddOrder
— mutation to add an order
Let’s take a look at our data first. For the simplicity of this tutorial, orders…