koa-ts
The best practice of building Koa2 with TypeScript. ไธญๆ
Usage
-
Run
npm init koa-ts
-
Install dependencies:
yarn
-
Rename
.env.example
to.env
, and runprisma db push
to synchronize the data model -
Start the server:
yarn dev
. visit: http://127.0.0.1:3000/apis/sessions
(Optional) the project has built-in a docker compose, run
yarn dev:db
to run database automatic.
Project Layout
โโโ app
โย ย โโโ controllers --- server controllers
โย ย โโโ helpers --- helper func (interceptor / error handler / validator...)
โย ย โโโ jobs --- task (periodic task / trigger task / email server...)
โย ย โโโ entities --- database entities/models
โย ย โโโ services --- adhesive controller and model
โโโ config
โย ย โโโ constants --- environment variable
โย โโโ koa.middlewares --- middlewares for Koa
โย โโโ routing.middlewares --- middlewares for Routing Controller
โย โโโ routing.options --- configs for Routing Controller
โย ย โโโ bootstrap --- lifecycle
โย ย โโโ interceptors --- global interceptor
โย ย โโโ utils --- pure functions for help
โโโ test --- utils for testcase
โโโ .env --- environment file
Feature
-
Separation configuration and business logic.
-
Export scheme model and interface, follow style of TypeScript.
-
Test cases and lint configuration.
-
The best practice for Dependency Injection in Koa project.
-
Get constraints on your data model with Prisma.
-
TypeScript hotload.
Lifecycle
-
app.ts
-> collect env varsconstants
-> collect env filesvariables.env
-
envs ready, call
bootstrap.before()
-
lift
routing-controllers
-> lift Koa middlewares -> registerContainer
for DI -
start Koa & invoke
bootstrap.after()
after startup
Databases
The project uses Prisma as the intelligent ORM tool by default. Supports PostgreSQL
, MySQL
and SQLite
.
- You can change the data type and connection method in the
.env
file - After each modification to file
/prisma/schema.prisma
, you need to runprisma migrate dev
to migrate the database. - After each modification to file
/prisma/schema.prisma
, you need to runprisma generate
to sync types.
About Environments
When nodejs is running, ENV
does not mean NODE_ENV
:
- After NodeJS project is built, we always run it as
NODE_ENV=PRODUCTION
, which may affect some framework optimizations. NODE_ENV
only identifies the NodeJS runtime, independent of the business.- You should use
ENV
to identify the environment.
For the data settings of each environment, you can refer to the following:
-
Development Mode (
ENV=development
): read configurations fromconfigs/constants/development.ts
file, but it will still be overwritten by.env
file. -
Production Mode (
ENV=production
): read configurations fromconfigs/constants/production.ts
file, but it will still be overwritten by.env
file.
Reference
LICENSE
This project is licensed under the MIT License. See the LICENSE file for more info.