Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript first argument path last argument callback

I'm trying to write a wrapper function around expressjs's app.get

The get (and other methods) accept as arguments, the path, some options, then the callback. But sometimes you can leave the options out and still work.

I used to do:

app.get(path, auth.loadUser, function () { 
  // example
})

so this doesn't work:

custom.get = function (path, callback) {
  // ?? missing a spot in the arguments array
  app.get(path, auth.loadUser, function () { 
    // example
  })
}

I need to be able to do this:

custom.get (path, callback) {
}

and this:

custom.get (path, auth.loadUser, callback) {
}

and have them both work at the same time, like in express.

So how can I write a wrapper function that knows that the first arg is the path and the last arg is the callback and everything else in the middle is optional?

like image 410
Harry Avatar asked Feb 24 '26 07:02

Harry


1 Answers

There are a couple of options. One is to check the type of the parameters passed to figure out what was passed. If you just want to modify one argument and you know it's passed in a particular location, you can just make a copy of the arguments array, modify that parameter and use .apply() to pass the modified arguments (however many there were) on to the original function call.

For the first option, the details of how you write the code depend upon what combinations of parameters you allow. Here's one method that allows zero or one option in the middle and callback is always at the end. This could be made more general with multiple options if you wanted. In that case, you would probably use the arguments array. Anyway, here's one version:

custom.get = function(path, option, callback) {
    // option is an optional parameter
    if (!callback || typeof callback != "function") {
        callback = option;   // callback must be the second parameter
        option = undefined;  // no option passed
    }
    if (option) {
        app.get(path, option, callback);
    } else {
        app.get(path, callback);
    }

}

For the second option, here's a generic version that lets you modify the path argument and pass all the rest of the parameters on through:

custom.get = function() {
    // assumes there is at least one parameter passed
    var args = [].slice.call(arguments);    // make modifiable copy of arguments array
    var path = args[0];

    // do whatever you want with the path

    args[0].path = path;
    return(app.apply(this, args));
}
like image 121
jfriend00 Avatar answered Feb 25 '26 21:02

jfriend00