How to create KOA route with both parameter and regex
Asked Answered
P

1

5

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

Pentalpha answered 6/1, 2015 at 20:26 Comment(0)
T
10

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);
Tarboosh answered 6/1, 2015 at 22:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.