I am writing a REST API with Express for a while now. I have been reading into Koa.js and it sounds very interesting, but I can't seem to figure out how to write proper ES6 features with Koa.js. I am trying to make a structured application and this is what I have now:
note: I am using the koa-route package,
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();
It works, but it looks and feels clunky. Is there a better way to do this?
Just because ES6 has classes, it does not mean you absolutely must use them when they might not be the right tool for the job. :)
Here's an example of how I usually do it. Please not that it is a way, not the way.
// 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);
Please note: This example is based on Koa 2 and Koa Router 7.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With