bornytm
bornytm

Reputation: 813

Consolidating Routes in Express.js

I'm a novice programmer working on a web app. As I have things right now there is a route for every single query to my database. I know there must be a way to use route parameters to direct the route to executing the right function but I am having problems in implementation.

Here is what my routes look like right now:

var database = require('./routes/database');

app.get('/query/type', database.type);
app.get('/query/test', database.test);
app.get('/query/another', database.another);
app.get('/query/onemore', database.onemore);

Each route is mapped to a function in the database.js file. I would like to try to implement something in the following format which would handle the queries with a single line:

app.get('/query/:query', database.query)

Where it executes whichever function is named in the parameter :query.

Is there an easy way of implementing this?

Upvotes: 0

Views: 168

Answers (1)

Third
Third

Reputation: 176

you can create a function that will parse the parameter and use associative array to build the function you want to execute then invoke it. see code below.

function parseParam(req, res) {
  var func = database[req.param('query')];
  func(req, res);
}

app.get('/query/:query', parseParam);

Upvotes: 1

Related Questions