From e5fdf8f542e64c1e9f2147c33c3ffd3fcd785d1e Mon Sep 17 00:00:00 2001 From: John Fawcett Date: Mon, 19 May 2014 15:41:20 -0500 Subject: [PATCH] add notfound error behavior for view --- README.md | 18 +++++++++++++++++- lib/dirac-middleware.js | 21 +++++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index c9cb8df..1645add 100644 --- a/README.md +++ b/README.md @@ -210,4 +210,20 @@ app.get( '/users/:id' ); ``` -### ```dm.find \ No newline at end of file +__Special Options:__ + +To override `error` and `not found` behavior: + +```javascript +app.get( '/users/:id' +, dm.param( 'id' ) +, dm.returning( 'id', 'name' ) +, dm.view( 'single_user_view', db.users, { + layout: 'admin/layout' + , notFound: function( req, res ){ res.render('404'); } + , error: function( error, req, res ){ res.render('error', { error: error }); } + }) +); +``` + +### TODO: FINISH DOCS \ No newline at end of file diff --git a/lib/dirac-middleware.js b/lib/dirac-middleware.js index 7e65335..c93b010 100644 --- a/lib/dirac-middleware.js +++ b/lib/dirac-middleware.js @@ -114,6 +114,19 @@ m.view = function(name, collection, options){ options = options || {}; options.method = options.method || 'find'; + var defaults = { + notFound: function( req, res ){ + return res.send(404); + } + , error: function( error, req, res ){ + return res.send(500); + } + }; + + for ( var key in defaults ){ + if ( !( key in options ) ) options[ key ] = defaults[ key ]; + } + return function(req, res){ collection = collection || req.collection; @@ -133,6 +146,14 @@ m.view = function(name, collection, options){ } args.push( function( error, results ){ + if ( error ){ + return options.error( error, req, res ); + } + + if ( !results ){ + return options.notFound( req, res ); + } + res.locals[ // If results is an array, we want to set the local // view variable to the plural form of that object type