0

I want to call an endpoint with a comma separated list, lets say I want to call with e.g. "hey,you" or "hey,you,abc"

If I call with

curl "http://localhost:8896/hey,you"

it is working with the following route:

router.get('/:id([a-z]{3},[a-z]{3})', (ctx) => {
  ctx.status = 200;
})

However this route is not working:

router.get('/:id([a-z]{3}(,[a-z]{3})*)', (ctx) => {
  ctx.status = 200;
})

I would expect this

(,[a-z]{3})*

to allow a repeated subgroup with , and 3 chars.

What am I doing wrong?

Kristoffer
  • 264
  • 2
  • 4
  • 16

1 Answers1

0

You can use /(^[a-z]{3}(?:,[a-z]{3})*$)/ to get the comma separated string, as a unique response, where you can split the results latter.

Alternatively, if you need regex to split them for you, you may use something like /,?([a-z]{3}),?/g. But I don't know how to enable the global flag in the routes, and it would also accept things like ,hey,you or hey,you,.

However, express route regex uses it's own regex rules with path-to-regexp package that doesn't allow catching groups (?:), and then, you can not define any repetition pattern as you need.

So it looks like the only way to make repetitions is with * (zero or more) or + (one or more), after the key name, so we could use something like /:id+([a-z]{3},?) where you can enable strict, sensitive and end.

You can test your regex paths with the Express Route Tester.

So it would be something like:

router.get('/:id+([a-z]{3},?)', (ctx) => {
  ctx.status = 200;
})

You may need to post-process the id to remove the ,.

Another alternative would be using a middleware.

Gonzalo
  • 400
  • 1
  • 9
  • This is not working either. It returns a syntax error `SyntaxError: Invalid regular expression: /^\/((?:[^\/]+?))\(\^\[a-z\]\{3\}(?:((?:?\:,[a-z]{3})(?:(?:?\:,[a-z]{3}))*))?\$\)(?:\/(?=$))?$/: Nothing to repeat` However there should also be at least one comma in the list. It's like koa-router doesn't support sub-groups. – Kristoffer Mar 24 '18 at 20:34
  • Sorry about that, I was no familiar with the regex limitations of path-to-regexp package. I updated the response, hope it helps now. – Gonzalo Mar 25 '18 at 09:36
  • If I use the updated answer and call with _http://localhost:8896/hey,you_ the ctx params ends up like: `{ "0": "you", "id": "hey," }` _http://localhost:8896/hey,you,hoo_ ends up like: `{ "0": "hoo", "id": "hey,you," }` It's not quite as expected as I would expect all the params to come in id param. Right now I will skip the regex part and do the check in the route. – Kristoffer Apr 03 '18 at 07:51
  • Sorry I could be of more help. I would use the middleware, as this regex is really limited, and if there is a way around, I'm not aware of it. – Gonzalo Apr 03 '18 at 08:29
  • Thanks for trying anyway. I didn't found any good middleware for koa doing this, so will use the workaround. – Kristoffer Apr 03 '18 at 09:26