TKoa - 使用 TypeScript 重构的 Node.js Koa开发框架

?Tkoa是使用 typescript 编写的 koa 框架!

尽管它是基于 typescript 编写,但是你依然还是可以使用一些 node.js 框架和基于 koa 的中间件。

不仅如此,你还可以享受 typescript 的类型检查系统和方便地使用 typescript 进行测试!

安装

TKoa 需要 >= typescript v3.1.0 和 node v7.6.0 版本。

$ npm install tkoa

Hello T-koa

import tKoa = require('tkoa');

interface ctx {
    res: {
        end: Function
    }
}

const app = new tKoa();

// response
app.use((ctx: ctx) => {
    ctx.res.end('Hello T-koa!');
});

app.listen(3000);
复制代码

Middleware

Tkoa 是一个中间件框架,拥有两种中间件:

  • 异步中间件
  • 普通中间件

下面是一个日志记录中间件示例,其中使用了不同的中间件类型:

async functions (node v7.6+):
interface ctx {
    method: string,
    url: string
}

app.use(async (ctx: ctx, next: Function) => {
    const start = Date.now();
    await next();
    const ms = Date.now() - start;
    console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
});
复制代码
Common function
// Middleware normally takes two parameters (ctx, next), ctx is the context for one request,
// next is a function that is invoked to execute the downstream middleware. It returns a Promise with a then function for running code after completion.

interface ctx {
    method: string,
    url: string
}

app.use((ctx: ctx, next: Function) => {
    const start = Date.now();
    return next().then(() => {
        const ms = Date.now() - start;
        console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
    });
});
复制代码

Getting started

Support

TypeScript

  • 大于等于 v3.1 版本

Node.js

  • 大于等于 v7.6.0 版本

License

MIT

转载于:https://juejin.im/post/5cb6c64351882532732290d6

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值