0

I wanna create 2 separate handlers for 2 routes below, first will do collections' actions, second - document related things. Two regex are needed for that.

That pattern

^\/api\/([\w]+)\/([\w]+)(\/([a-f0-9]{24}))?\/?\??.*$

covers all two cases

1)

/api/appslug/collectionname
/api/appslug/collectionname/
/api/appslug/collectionname?key=val
/api/appslug/collectionname/?key=val
/api/appslug/collectionname?key=val&hello=there
/api/appslug/collectionname/?key=val&hello=there

2)

/api/appslug/collectionname/5919a81f318139c5157636f9
/api/appslug/collectionname/5919a81f318139c5157636f9/
/api/appslug/collectionname/5919a81f318139c5157636f9?key=val
/api/appslug/collectionname/5919a81f318139c5157636f9/?key=val
/api/appslug/collectionname/5919a81f318139c5157636f9?key=val&hello=there
/api/appslug/collectionname/5919a81f318139c5157636f9/?key=val&hello=there

How to create separate pattern for routes containing mongo id ?

Thanks!

Xitroff
  • 101
  • 10

1 Answers1

1

The optional (\/([a-f0-9]{24}))? is responsible for that /5919a81f318139c5157636f9 part. Remove it from for collections (and also require the question mark to be mandatory if parameters exit to distinguish them from document ID):

^\/api\/([\w]+)\/([\w]+)(?:\/?\?.*|\/)?$

(demo: https://regex101.com/r/WEoEA5/1)

and make it mandatory for documents:

^\/api\/([\w]+)\/([\w]+)\/([a-f0-9]{24})\/?\??.*$
Dmitry Egorov
  • 9,542
  • 3
  • 22
  • 40
  • 1
    Thanks for help, but unfortunately your first pattern covers all two cases. – Xitroff May 16 '17 at 14:17
  • actually, i can place ^\/api\/([\w]+)\/([\w]+)\/([a-f0-9]{24})\/?\??.*$ that route pattern before the second and it will work well, but i wanna get another solution. – Xitroff May 16 '17 at 14:20
  • @Xitroff: yes, you're right. I forgot to make `?` mandatory. Please see the updated answer. – Dmitry Egorov May 16 '17 at 14:27