Biba
Biba

Reputation: 758

How to create KOA route with both parameter and regex

How can I accomplish the following KOA route handler:

app.get("/Chicago_Metro/Cicero_City", myFunctionHandler1)
app.get("/Cook_County/Cicero_City", myFunctionHandler2)

and end up with "Chicago" as the parameter to be passed for "metro" OR "Cook" passed for county and "Cicero" passed for "city in my handlers below:

function *myFunctionHandler1(metro, city) {
...
}

function *myFunctionHandler2(county, city) {
...
}

I was considering Regex in the route but I never saw how that can mix with :param.

NOTE: I need to keep that path syntax since it's already SEO'ed and indexed as above.

Worst case probably I will end up with the whole name as parameter and handle it inside a single handlerFn and test the ending to _metro or _county or _city

Upvotes: 5

Views: 6318

Answers (1)

James Moore
James Moore

Reputation: 1901

Regex Capture Group

var koa   = require('koa'),
    route = require('koa-router'),
    app   = koa();

app.use(route(app));

app.get(/^\/(.*)(?:_Metro)\/(.*)(?:_City)$/, function *(){
    var metro = this.params[0];
    var city = this.params[1];
    this.body = metro + ' ' + city;
});

app.get(/^\/(.*)(?:_County)\/(.*)(?:_City)$/, function *(){
    var county = this.params[0];
    var city = this.params[1];
    this.body = county + ' ' + city;
});

app.listen(3000);

Upvotes: 10

Related Questions