pokemen v1.0.2
koa-ts
The best practice of building Koa2 with TypeScript. 中文
Usage
This layout requires NodeJS v12+
Run
npm init koa-ts.Install dependencies:
yarnornpm i.Start the server:
yarn devornpm dev. visit: http://127.0.0.1:3000/apis/sessions
(Optional) if you need database, set useDatabase to true.(in
configs/customs.ts).(Optional) the project has built-in a docker-compose, run
npm run mongolift mongodb 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
│ ├── environments --- environment variable
│ ├── koa.middlewares --- middlewares for Koa
│ ├── routing.middlewares --- middlewares for Routing Controller
│ ├── routing.options --- configs for Routing Controller
│ ├── connection --- database connection
│ ├── bootstrap --- lifecycle
│ ├── customs --- user settings
│ └── interceptors --- global interceptor
│ └── utils --- pure functions for help
└── test --- utils for testcase
├── variables.env --- environment fileFeature
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.
Deploy by ncc.
TypeScript hotload.
Lifecycle
app.ts-> collect env varsenvironments-> collect env filesvariables.envenvs ready, call
bootstrap.before()configs/connection.tsconnecting external services (e.g. DB / Redis...)lift
routing-controllers-> lift Koa middlewares -> registerContainerfor DIstart Koa & invoke
bootstrap.after()after startupconfigs/connection.tsconnected -> invokebootstrap.connected()
Databases
You can link multiple databases (mysql / mongo etc.), each database can link configurations of multiple environments:
- The database will load the configs of
ormconfig.jsfile. - You can specify link configs of multiple environments under folder
configs/environments. - You can specify encrypted information in file
variables.env. It is not recommended to add filevariables.envto version control. - You can still manually set
process.envto override all environment variables.
About Environments
Development Mode (
NODE_ENV=development): read configurations fromconfigs/environments/development.tsfile, but it will still be overwritten byvariables.envfile.Production Mode (
NODE_ENV=production): read configurations fromconfigs/environments/production.tsfile, but it will still be overwritten byvariables.envfile.
Reference
LICENSE
This project is licensed under the MIT License. See the LICENSE file for more info.
4 years ago