Giter VIP home page Giter VIP logo

koa-ts's Introduction

koa-ts

The best practice of building Koa2 with TypeScript. 中文


Usage

  1. Run npm init koa-ts

  2. Install dependencies: yarn

  3. Rename .env.example to .env, and run prisma db push to synchronize the data model

  4. 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

  1. app.ts -> collect env vars constants -> collect env files variables.env

  2. envs ready, call bootstrap.before()

  3. lift routing-controllers -> lift Koa middlewares -> register Container for DI

  4. 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 run prisma migrate dev to migrate the database.
  • After each modification to file /prisma/schema.prisma, you need to run prisma 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 from configs/constants/development.ts file, but it will still be overwritten by .env file.

  • Production Mode (ENV=production): read configurations from configs/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.

koa-ts's People

Contributors

chirigg avatar dependabot[bot] avatar jokereven avatar leekoho avatar unix avatar wittbulter avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

koa-ts's Issues

在PRODUCTION模式下,controller无法访问到service

Type:

  • Bug
  • Feature
  • Help

Description:

在env=DEVELOPMENT模式下运行,没有任何的问题
但是如果在env=PRODUCTION模式下运行时,controller访问service的函数时,是undefined

例如:

import { UserService } from '../services'

@JsonController()
@Service()
export class UserController {

  constructor(private userSerivce: UserService) { }

  @Post('/user/login')
  async login(
    @BodyParam('code') code: string
  ): Promise<any> {
    if (!code) {
      throw new BadRequestError('code is required')
    }
    let res = await this.userSerivce.loginByCode(code)
    console.log(this.userSerivce.loginByCode) // undefined
    return res
  }
}

mocha test issue

Type:

  • Bug
  • Feature
  • Help

Description:

Follow these steps:

  1. git clone [email protected]:unix/koa-ts.git
  2. yarn install
  3. yarn test

Output error message:

yarn test
$ mocha
Error: Cannot find module 'configs/utils'
    at Function.Module._resolveFilename (module.js:547:15)
    at Function.Module._load (module.js:474:25)
    at Module.require (module.js:596:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/Users/foo/Desktop/source/koa-ts/app.ts:2:1)
    at Module._compile (module.js:652:30)
    at Module.m._compile (/Users/foo/Desktop/source/koa-ts/node_modules/ts-node/src/index.ts:439:23)
    at Module._extensions..js (module.js:663:10)
    at Object.require.extensions.(anonymous function) [as .ts] (/Users/foo/Desktop/source/koa-ts/node_modules/ts-node/src/index.ts:442:12)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Module.require (module.js:596:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/Users/foo/Desktop/source/koa-ts/test/utils.nyc.ts:4:1)
    at Module._compile (module.js:652:30)
    at Module.m._compile (/Users/foo/Desktop/source/koa-ts/node_modules/ts-node/src/index.ts:439:23)
    at Module._extensions..js (module.js:663:10)
    at Object.require.extensions.(anonymous function) [as .ts] (/Users/foo/Desktop/source/koa-ts/node_modules/ts-node/src/index.ts:442:12)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Module.require (module.js:596:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/Users/foo/Desktop/source/koa-ts/test/apis/session.ts:1:1)
    at Module._compile (module.js:652:30)
    at Module.m._compile (/Users/foo/Desktop/source/koa-ts/node_modules/ts-node/src/index.ts:439:23)
    at Module._extensions..js (module.js:663:10)
    at Object.require.extensions.(anonymous function) [as .ts] (/Users/foo/Desktop/source/koa-ts/node_modules/ts-node/src/index.ts:442:12)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Module.require (module.js:596:17)
    at require (internal/module.js:11:18)
    at /Users/foo/Desktop/source/koa-ts/node_modules/mocha/lib/mocha.js:250:27
    at Array.forEach (<anonymous>)
    at Mocha.loadFiles (/Users/foo/Desktop/source/koa-ts/node_modules/mocha/lib/mocha.js:247:14)
    at Mocha.run (/Users/foo/Desktop/source/koa-ts/node_modules/mocha/lib/mocha.js:576:10)
    at Object.<anonymous> (/Users/foo/Desktop/source/koa-ts/node_modules/mocha/bin/_mocha:637:18)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Function.Module.runMain (module.js:693:10)
    at startup (bootstrap_node.js:191:16)
    at bootstrap_node.js:612:3
error Command failed with exit code 1.

路过,关于各参数的说明?

Type:

  • Bug
  • Feature
  • Help

Description:
只是看package.json只能猜个大概...
感觉项目结构蛮经典的..
不过好像没有配热更新?
有考虑加上么...?

Keep this up to date?

Type

  • Bug
  • Feature
  • Help

Description

Any intentions on keeping this up to date? As a big Koa user, I'd love to lend a hand where I can :)

help:如何注入errorHandle

Type:

  • Bug
  • Feature
  • Help

Description:
在koa.middlewares.ts文件中注入一个错误处理,没有注入成功,应该如何注入?
...
app.use(errorHandle) //这个位置注入的
app.use(bodyParser())

请问怎么返回文件呢?

Type:

  • Bug
  • Feature
  • Help

Description:
刚接触 koa,网上找了各种方式都试过了,发现在后端文件都下载了,但是返回的时候还是只是一个空对象 {},以为跟 JsonController 有关,换成 Controller 并且使用 ContentType 设置了文件类型为 ""application/vnd.openxmlformats-officedocument.wordprocessingml.document",测试虽然会调用浏览器下载功能,但是打开文件还是个空对象的字符串在文件里。

希望大佬能指点一下 😂

请教一下ConnectionManager的用法

Type:

  • Bug
  • Feature
  • Help

Description:

数据库:Mysql 5.7

我在使用Repository的过程中遇到一些小问题:
首先我定义了一个Service,在对应的Controller中调用Service时出现ConnectionNotFoundError: Connection "default" was not found.报错,打断点排查发现走至constructor给reponsitory赋值的这一步就出现了异常。

@Service()
export class IpProxyService {
    repository:Repository<IpProxy>
    constructor() {
        this.repository = getRepository(IpProxy)
    }
     ..............
}

经过排查以及查阅官方文档,我发现系connection.ts中定义的connectionManager初始化方式的差异所致:
在大大的项目中,使用的是new ConnectionManager()方法,而如果需要像大大给的session.service.ts演示中的Repository使用方法一致的话,需要变成getConnectionManager()与您在session.services.ts中演示的不一致。

以下摘自TypeORM文档
This is not a general way of creating a connection, but it may be useful for some users. For example, users who want to create connection and store its instance, but have to control when the actual "connection" will be established. Also you can create and maintain your own ConnectionManager:

import {getConnectionManager, ConnectionManager, Connection} from "typeorm";

const connectionManager = new ConnectionManager();

const connection = connectionManager.create({
    type: "mysql",
    host: "localhost",
    port: 3306,
    username: "test",
    password: "test",
    database: "test",
});
await connection.connect(); // performs connection

But note, this way you won't be able to use getConnection() anymore - you'll need to store your connection manager instance and use connectionManager.get to get a connection you need.

Generally avoid this method and avoid unnecessary complications in your application, use ConnectionManager only if you really think you need it.

文档中说到new ConnectionManager(); 并不是一个比较常见的用法,需要开发者自己手动存储这个ConnectionManager实例(比如说挂载在global上),然后在各个地方引用才可以使用。

使用这种方式连接,在我个人的理解里面,使用的过程中应该是不能使用typeorm提供的那些方法去获取getConnection以及getRepository,需要直接维护/获取存储的ConnectionManager实例。

不知道是不是我使用上出现了问题,麻烦大大看这一大片文字了。

运行出错

E:\ts\koa-ts>yarn dev
yarn run v1.22.0
$ export NODE_ENV=development; nodemon --config nodemon.json
'export' 不是内部或外部命令,也不是可运行的程序
或批处理文件。

run to stop

Type:- [ ] Help

Console:
PS C:\Users\LENOVO\Desktop\数字权益平台\test\koa-ts> yarn
yarn install v1.22.10
[1/5] Validating package.json...
[2/5] Resolving packages...
info [email protected]: The platform "win32" is incompatible with this module.
info "[email protected]" is an optional dependency and failed compatibility check. Excluding it from installation.
[4/5] Linking dependencies...
warning " > [email protected]" has incorrect peer dependency "[email protected]".
[5/5] Building fresh packages...
Done in 22.50s.
yarn run v1.22.10
$ export NODE_ENV=development; nodemon --config nodemon.json
'export' 不是内部或外部命令,也不是可运行的程序
或批处理文件。
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
PS C:\Users\LENOVO\Desktop\数字权益平台\test\koa-ts> yarn dev
yarn run v1.22.10
$ set NODE_ENV=development; nodemon --config nodemon.json
Done in 0.13s.

Description:
34/5000
node:v12.21.0
I'm using Windows, but when I run the "yarn dev" command I get "export NODE_ENV=development; "Nodemon --config nodemon. Json" exception.Then I changed the expost in the package.json file to set.Run the "yarn dev" command.As a result, the program terminated.

help: mongodb如何分页查询

Type:

  • Help

Description:
使用mongodb如何分页查询,使用createQueryBuilder提示:Query Builder is not supported by MongoDB

打包失败

Type:

  • [ x ] Bug
  • Feature
  • Help

Description:
ts配置中的emitDeclarationOnly导致编译失败
TS5069: Option 'emitDeclarationOnly' cannot be specified without specifying option 'declaration' or option 'composite'.

删除后可以编译成功,但是启动服务时又报错 NODE_ENV=development node releases/index
import Environment from 'configs/environments'
^^^^^^

SyntaxError: Cannot use import statement outside a module

PrimaryGeneratedColumn use

Type:

  • [] Help
    Description:
    PrimaryGeneratedColumn()
    id: number
    创建后的字段怎么变成了_id: Object('uuid')类型了?查找了typeorm没找到问题所在,望指教!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.