Create a NodeJS API with Koa and TypeScript
In this tutorial series you will learn how to create a RESTful / JSON API using Koa 2, TypeScript, and Redis. You'll also work in a (partially) test driven development (TDD) fashion. I say partially, as often it's easiest to do a little "proof of concept" first, before writing tests.
By the end of this tutorial series you will have:
- Created a new Koa project
- Added TypeScript, third party typings, and created your own type definitions
- Set up Jest, and created tests for all the API endpoints
- Used Redis (through Docker) as a plug-in storage solution
- Created routes to handle
- Added validation logic for incoming data
The goal of this tutorial series is to create a tested / testable JSON API that handles a single resource, which in our case will be a list of Games. You are completely free to switch this up.
You may be wondering: "What is Koa?"
Koa is a new web framework designed by the team behind Express, which aims to be a smaller, more expressive, and more robust foundation for web applications and APIs. By leveraging async functions, Koa allows you to ditch callbacks and greatly increase error-handling. Koa does not bundle any middleware within its core, and it provides an elegant suite of methods that make writing servers fast and enjoyable.
That is taken straight from the docs.
Adding TypeScript makes some things easier, and some things that much harder. We'll make use of TypeScript to ensure the 'shape' of our data is as expected.
Redis is an in-memory data store which we will use as a very lightweight database. You could switch this out for a SQL database such as Postgres, but Redis's lists will serve our purposes just fine. We'll use Docker to run Redis (though you can run it any way you like), to make things even easier for ourselves.
Finally, validation is extremely useful - and something TypeScript won't be able to help us with directly. We'll make use of a third party library to make validation a breeze.
Ready to get started? Me too. Let's roll.