Showing posts with label function. Show all posts
Showing posts with label function. Show all posts

Wednesday, March 23, 2016

An Express middleware to check if a resource exists

After writing a similar code snippets for tens of times, I decided to write a middleware to handle it. The scenario is quite common. You want to check if an resource exists before going to the next step of processing. In my applications,  it is a query in the MongoDB.


/**
 * A middleware to check if id exists in collection
 * app.get('/resources/:id/', exist('id', collection), function(req, res){...}}
 * @param  {String} id            the parameter name of item id in req object
 * @param  {Model} collection     the collection model
 * @return {Function}             the middleware
 */
function exist(id, collection) {
  return function (req, res, next) {
    collection.findById(req.params[id]).exec(function (err, item) {
      if (err) {
        console.error(err);
        return res.send(500, 'Something wrong!');
      }

      if (!item) {
        return res.send(404, 'item ' + req.params[id] + ' not found');
      }
      
      req[req.params[id]] = item;
      next();
    });
  };
}

Friday, November 27, 2009

Rich Hickey on function, time, and process

All the concurrency and timing puzzles suddenly become reasonable after listening to his talk titled "Are we there yet". I borrowed the book of "Process and Reality" from the library, and started to learn Whitehead's system.

If you do multithreading programming, or play with JavaScript and XHR, or like Erlnag, Clojure, or Scala, then you would perhaps enjoy his talk.