sundar
sundar

Reputation: 105

Dynamic routes in Koa?

Let's say I have an array of routes that looks like this:

var routes = [
    {
        route: '/',
        handler: function* () { this.body = yield render('home', template.home) }
    },
    {
        route: '/about',
        handler: function* () { this.body = yield render('about', template.about) }
    }
];

What would be the best way to app.use them? I've tried doing it (with koa-route as my middleware) like this:

Promise.each(routes, function(r) {
    app.use(route.get(r.route, r.handler));
}).then(function() {
    app.use(function *NotFound(next) {
        this.status = 404;
        this.body = 'not found';
    });
});

But it doesn't seem to be working (I've also tried a plain routes.forEach). What am I doing wrong?

Upvotes: 2

Views: 2271

Answers (1)

sundar
sundar

Reputation: 105

After some more tinkering, I've managed to get the above code working by doing this:

var routes = {
    '/': function* () { this.body = yield render('home', template.home); },
    '/about': function* () { this.body = yield render('about', template.about); }
};

app.use(function* respond() {
    if (routes[this.request.url])
        yield routes[this.request.url].call(this);
});

I'll accept this answer when I can, but should anyone post a better solution, I'll happily accept theirs.

Upvotes: 4

Related Questions