Koa
Koa is a web server framework designed to create backend APIs.
Installation#
Install koa, koa-router, koa-cors, and supertest. Koa-cors will enable you to hit your API from different domains (don't install if you don't need). Supertest allows you to easily run tests on your endpoints.
The guide below assumes you've run tsdx to generate a basic library with TypeScript, Jest, etc. (or that you've set up the build yourself already such that you have Jest and that npm start watches for changes and builds artifacts in the dist directory, also package.json main should point to your entry file in dist i.e. "main": "dist/index.js" - this will tell nodemon where to enter).
Adding Code and Tests#
Adapted from this article.
In src/index.ts
In src/app.ts
In test/app.test.ts
You should now be able to run the tests with npm run test to test your endpoint.
In order to run your server you can run npm start and node dist/index.js.
To run in development with changes being watched and automatic restarts, you'll need to add the following to your package.json scripts section.
Then you can run this in one terminal (runs the build in a watch mode):
and this in another (runs the built server code from the dist directory and restarts server after any changes):
You should now be able to hit the endpoint via localhost.