Cory Klein
Cory Klein

Reputation: 55690

What does ":op?" mean in a url route?

Looking at some Node.js Express code, I see this route list:

app.all('/user/:id/:op?', user.load);
app.get('/user/:id', user.view);
app.get('/user/:id/view', user.view);
app.get('/user/:id/edit', user.edit);
app.put('/user/:id/edit', user.update);

When running this, I notice that requests for /user/:id actually get routed to user.load. Being new to this, I was surprised.

What does the :op? do in the first line that causes it to catch a less specific route? I couldn't find any instance of :op? in the Express documentation.

Upvotes: 2

Views: 745

Answers (2)

VisioN
VisioN

Reputation: 145408

From the documentation of app.all:

This method is extremely useful for mapping "global" logic for specific path prefixes or arbitrary matches.

Now lets have a look at the routing.

Question mark ? in app.all('/user/:id/:op?', user.load) means that the parameter :op (can be considered as "operation") in the route is optional.

As the all method call is placed before other route calls, everything that matches the routes /user/:id/, /user/:id/view, and /user/:id/edit will first pass through the user.load method. It is worth to mention, that :op as a parameter most probably doesn't play any specific role in user.load but works as a placeholder in the route.

Most probably this approach helps to check if the entity exists in the database before continuing with view or edit operations.

Also, keeping in mind @apsillers comment and the referred citation from the docs, user.load method might have a next() call in the end of the callback in order to progress with the other route matches.

Upvotes: 2

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324650

I have absolutely no idea what this code is, or what it does.

But I would guess that, just as :id is used to placehold the ID of the user, :op? would be used to optionally (?) placehold an operation (such as the view or edit ones we see below it)

Upvotes: 0

Related Questions