将Koa.js与ES6一起使用

Use Koa.js with ES6

本文关键字:一起 ES6 Koa js      更新时间:2023-09-26

我正在用Express编写一个REST API已有一段时间了。我一直在读Koa.js,它听起来很有趣,但我似乎不知道如何用Koa.js编写正确的ES6功能。我正在尝试制作一个结构化的应用程序,这就是我现在所拥有的:

注意:我使用的是koa路由包

let koa = require('koa');
let route = require('koa-route');
let app = koa();

class Routes {
    example() {
        return function* () {
            this.body = 'hello world';
        }
    }
}
class Server {
    constructor(port) {
        this.port = port;
    }
    addGetRequest(url, func) {
        app.use(route.get('/', func());
    }
    listen() {
        app.listen(this.port);
    }
}
const port = 8008;
let routes = new Routes();
let server = new Server(port);
server.addGetRequest('/', routes.example);
server.listen();

它很管用,但看起来和感觉都很笨重。有更好的方法吗?

仅仅因为ES6有类,并不意味着当它们可能不是适合作业的工具时,绝对必须使用它们。:)

这是我通常如何做的一个例子。请不要说这是的方式,而不是方式。

// api/exampleApi.js
const controller = {
  getExample: (ctx) => {
    ctx.body = { message: 'Hello world' };
  }
}
export default function (router) {
  router.get('/example', controller.getExample);
}
// server.js
import Koa from 'koa';
import KoaRouter from 'koa-router';
import exampleApi from 'api/exampleApi';
const app = new Koa();
const router = new KoaRouter();
exampleApi(router);
app.use(router.routes());
app.listen(process.env.PORT || 3000);

请注意:此示例基于Koa 2和Koa路由器7。