matchit icon indicating copy to clipboard operation
matchit copied to clipboard

Support optional last param

Open MarkoMackic opened this issue 2 years ago • 7 comments

Let's suppose you have common handler for REST type API on some resource, like /companies/.

So usual request pattern is :

  • GET /companies(/?) - > get all companies
  • GET /companies/:id -> get specific company
  • PUT/POST/PATH/DELETE /companies/:id -> do something to specific company

Now all of the work can be done by the same handler , if it knows if :id is present.

I'm suggesting introduction of optional last param, e.g. router.insert("/companies/:id?", whatever);

  • accepts route /companies/
  • accepts route /companies/some_id

router.insert("/companies/*catch_all?", whatever)

  • same as above for route without param
  • and general catchall behaviour is applied if param exists

Optional params should be supported only if they are in the route end ( which is obvious ) .

This would be easier than writing double insert in code that uses the library.

MarkoMackic avatar Oct 26 '22 13:10 MarkoMackic

I agree this would be useful to have, I would accept a pull request implementing this :)

ibraheemdev avatar Nov 09 '22 03:11 ibraheemdev

I'll see if I can do this :)

MarkoMackic avatar Feb 08 '23 12:02 MarkoMackic

I've run into a situation where I need an optional parameter, but not at the end.

I'm implementing the Docker registry. Docker image tags can be ubuntu or library/ubuntu. Therefore, the path the client requests will be in the form of /v2/:group?/:name/blobs/uploads.

Attempting to add each of the two routes will result in a conflict error.

cometkim avatar Mar 27 '23 15:03 cometkim

Well you can't add optional params in the middle :) That's not how it works. It's not logical. For that case you'd have two routes.

MarkoMackic avatar Mar 28 '23 08:03 MarkoMackic

For that case you'd have two routes.

I tried. But I got a conflict error. is this a bug?

panicked at 'failed to register Post route for /v2/:name/blobs/uploads/ pattern: insertion failed due to conflict with previously registered route: /v2/:pathname/:name/blobs/uploads/'

cometkim avatar Mar 29 '23 14:03 cometkim

That's https://github.com/ibraheemdev/matchit/issues/13, it would have to be /v2/:name/blobs/uploads/ and /v2/:name/:subname/blobs/uploads/ (the first parameter's name has to stay the same).

ibraheemdev avatar Mar 29 '23 20:03 ibraheemdev

@cometkim I suggest taking a look at this issue #39 Docker Registry API V2 can contain more than 2 segments

Bromles avatar Aug 08 '23 19:08 Bromles