Giter VIP home page Giter VIP logo

koatty's Introduction

koatty

Koa2 + Typescript + IOC = koatty.

Use Typescript's decorator implement IOC and AOP.

Version npmnpm Downloads

New features

  • HTTP、HTTPS、HTTP2、gRPC、WebSocket server.
  • Support loading environment configuration, parsing command line parameters (process.argv) and environment variables (process.env)
  • @ExceptionHandler() Register global exception handling
  • graceful shutdown and pre-exit event
  • custom decorator based on app events

Documentation

koatty_doc_CN (In progress💪)

Installation CLI tools

npm i -g koatty_cli

Quick Start

1.Create Project

kt new projectName

2. Install deps

cd ./projectName

npm i

3. Start up

npm run dev

// or
npm start

Code style

default Controller:

import { Controller, Autowired, GetMapping, RequestBody, PathVariable,
 PostMapping, RequestMapping, RequestMethod, Valid, Output } from "koatty";
import { TestDTO } from "../model/dto/TestDTO";
import { TestService } from "../service/TestService";
import { App } from "../App";

@Controller()
export class IndexController {
    app: App;
    ctx: KoattyContext;

    @Autowired()
    private testService: TestService;

    /**
     * constructor
     *
     */
    constructor(ctx: KoattyContext) {
        this.ctx = ctx;
    }

    @RequestMapping("/:name", RequestMethod.ALL)
    async default(@PathVariable("name") @Valid("IsNotEmpty") name: string) {
        try {
            const info = await this.testService.sayHello(name);
            return Output.ok(this.ctx, "success", info);
        } catch (err: Error) {
            return Output.fail(this.ctx, err.message));
        }
    }

    @PostMapping("/test")
    @Validated() //need DTOClass
    test(@RequestParam() params: TestDTO) {
        return Output.ok(this.ctx, "test", params);
    }
}

How to do Unit Testing

only support jest UT framework now

import request from 'supertest';
import { ExecBootStrap } from 'koatty';
import { App } from '../src/App';

describe('UT example', () => {

  let server: any;
  beforeAll(async () => {
    jest.useFakeTimers();
    const appInstance = await ExecBootStrap()(App);
    server = await appInstance.listen();
  });

  afterAll(done => {
    server.close();
    done();
  });

  it('request', async () => {
    const rsp = await request(server).get('/');
    expect(rsp.status).toBe(200);
  });
});

How to debug

if you use vscode , edit the .vscode/launch.json , like this:

{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "node",
            "request": "launch",
            "name": "TS Program",
            "args": [
                "${workspaceRoot}/src/App.ts" 
            ],
            "runtimeArgs": [
                "--nolazy",
                "-r",
                "ts-node/register"
            ],
            "sourceMaps": true,
            "cwd": "${workspaceRoot}",
            "protocol": "inspector",
            "outputCapture": "std",
            "internalConsoleOptions": "neverOpen"
        }
    ]
}

Select TS Program to debug run. Try to call http://localhost:3000/ .

Example

Check out the quick start example.

koatty's People

Contributors

dependabot[bot] avatar richenlin 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

koatty's Issues

confused about the view location

Hi There, from the demo project https://github.com/thinkkoa/koatty_demo/ I found you placed the views in static/html.

I can unstand that the folder static is the common foler to both src and dist. However if you place the views in static folder, it means the visiters can visit it directly without route. It is not safe in my point of view. Do you have any plan to improve it?

使用koa-session时,返回报错

koatty确实是很优雅的框架,但在开发过程中,配合koa-session与koatty使用时,使用BaseController的return this.ok(res)时,会导致返回抛出错误(404),如下图
image
但改用this.ctx.body = res返回时,则一切正常

我的SessionMiddleware.ts文件如下:
image

业务代码,UserController.ts
image

运行 npm start 时卡住

创建项目并安装依赖后,运行 npm start 会卡住,3000端口无法访问。如果运行 npm run dev 则可正常启动。

image

使用 npm start 启动后,无法使用 Ctrl+C 退出。如果运行 npm run dev,则可正常使用 Ctrl+C 退出,但计划任务仍在运行。

image

can you pls give any mongo configuration demo?

I found the mysql and redis config in the db.ts, however there is no mongodb config there.

By the way, this framework is the finished and successfull one or it is just under constructing and can not be used for a real project yet? Pls let me known, thank you!

when I use a module which used to scrapy data via https, error shows

Hi @richenlin

Sorry for troubling you!

1111

The following are the console screenshot:
2222

33333

Do you have any idea that how I can fixed this?

I guess the moudle which I used to scrapy the cod16 data through https schema. Some certification problem prevent the this.ok() output.

By the way, I can not find how to acquire the get params ( like someUrl?a=1&b=2, I want to get param a and b in the controller action.) from you document https://thinkkoa.github.io/koatty_doc/#/?id=getname-string

关于没有配置的页面展示

你好,用了你的这个koatty包后能正常使用。配置了首页和一个路由页/search,都能正常使用,目前有个问题。像某些乱写的比如/sea这种没有配置的页面访问后,直接报错暴露了我的后台路径了。想使没配置的页面(除了首页和"/search")直接访问一个静态404页面 该怎么配置呢?谢谢

Error: RequestBody decorator is only used in controllers class.

Am unable to run the app and facing this error message. Google Search did not help at all. Error shown at the line 10(marked with Arrow). Same RequestBody decorator works just fine in other controllers.

`
import { Controller, BaseController, GetMapping, PostMapping, RequestBody, Header, Middleware, Param } from "koatty";
import { App } from '../../App';
import { google } from 'googleapis';

@controller()
export class InAppVerifycontroller extends BaseController {
app: App;

@PostMapping("/verifyPurchase")
async verifyPurchase(@RequestBody() requestBody: any) {  <-------------------------
    const packageName = requestBody.post.packageName;
    const subscriptionId = requestBody.post.subscriptionId;
}

}`

Logs:

[2020-10-06 21:11:10.405] [ERROR] Error: RequestBody decorator is only used in controllers class.
at /Users/dhanasekarapandiansrinivasan/Development/middleware/node_modules/koatty/src/core/RequestMapping.ts:214:19
at /Users/dhanasekarapandiansrinivasan/Development/middleware/node_modules/tslib/tslib.js:101:41
at DecorateProperty (/Users/dhanasekarapandiansrinivasan/Development/middleware/node_modules/reflect-metadata/Reflect.js:553:33)
at Object.decorate (/Users/dhanasekarapandiansrinivasan/Development/middleware/node_modules/reflect-metadata/Reflect.js:123:24)
at Object.__decorate (/Users/dhanasekarapandiansrinivasan/Development/middleware/node_modules/tslib/tslib.js:95:96)
at Object. (/Users/dhanasekarapandiansrinivasan/Development/middleware/src/controller/InApp/InAppVerifycontroller.ts:10:5)
at Module._compile (internal/modules/cjs/loader.js:1138:30)
at Module._compile (/Users/dhanasekarapandiansrinivasan/Development/middleware/node_modules/ts-node/src/index.ts:858:23)
at internal/modules/cjs/loader.js:1158:10
at Object..ts (/Users/dhanasekarapandiansrinivasan/Development/middleware/node_modules/ts-node/src/index.ts:861:12)

errors after run "npm install"

error111

Dear Author,
Today, I start a new project by the following steps:

  1. koatty new projectName
  2. cd ./projectName
  3. npm install

then the above errors shows, pls help.

Thank you in advance!

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.