copenndthagen
copenndthagen

Reputation: 50732

REST endpoint simulation via ExpressJS

If I have the below endpoints configured in my ExpresssJS config file server.js

// Generic    
app.post('/mycontext/:_version/:_controller/:_file', (req, res) => {
      const {_version,_controller,_file} = req.params;
      const mockDataFile = path.normalize(path.join(mockRoot,`${_version}/${_controller}/${_file}.json`));
    });

// Specific    
    app.post('/mycontext/v1/mycontroller/myendpoint', (req, res) => {
    
    });

For an endpoint invoked from UI as say /mycontext/v1/mycontroller/myendpoint, which of these 2 would get mapped ? Does the order of defining these configs matter in any way ?

Upvotes: 1

Views: 47

Answers (1)

Majid Parvin
Majid Parvin

Reputation: 5012

The order is first come first serve.

ExpressJS calculates the priority of a route based on the specificity of its path and the order by which they are declared. Routes are ordered from the most specific to the less specific one.

the first one will be hit:

app.post('/mycontext/:_version/:_controller/:_file', (req, res) => {
      const {_version,_controller,_file} = req.params;
      const mockDataFile = path.normalize(path.join(mockRoot,`${_version}/${_controller}/${_file}.json`));
    });

Bear in mind that in ExpressJS there's no built-in way to declare our routes as a list ordered by priority.

Although, You can declare specific routes always before generic routes as a best practice.

Upvotes: 2

Related Questions