4

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?

DevNebulae
  • 4,566
  • 3
  • 16
  • 27

1 Answers1

7

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.

Jeff
  • 12,085
  • 12
  • 82
  • 152
  • I discovered the roadmap for Koa v2 today: https://github.com/koajs/koa/issues/533 . They rewrote it to work with ES6, but I am gonna wait until it's the definitive version. Thanks for the answer anyway! – DevNebulae May 12 '16 at 16:57