API Version Routing - change code from Express to KOA

1.1k views Asked by At

I am trying to create different routes for different API versions.

I saw the following stackoverflow post: How do you handle api version in a Node/Express app

which linked me to this express js code: http://j-query.blogspot.ca/2013/01/versioned-apis-with-express.html

I am trying to copy the code and convert it to KOA (which I am a bit new to..)

How do I do this?

1

There are 1 answers

0
James Moore On

Something like this would seem to work:

let koa     = require('koa'),
    router  = require('koa-router'),
    app     = koa();

let v1 = new Router({
  prefix: '/v1'
});

// responds to "/v1"
v1.get('/', ...) 
v1.post('/', ...) 

app.use(v1.routes());
app.use(v1.allowedMethods());

let v2 = new Router({
  prefix: '/v2'
});

// responds to "/v2"
v2.get('/', ...) 
v2.post('/', ...) 

app.use(v2.routes());
app.use(v2.allowedMethods());

app.listen(3000);