dispatcher.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. const _pages = require('../dist/pages.json');
  2. const _renderer = require('./page-renderer');
  3. // multi-type support
  4. // @see https://github.com/expressjs/express/blob/master/examples/error-pages/index.js
  5. function dispatchRequest(page, httpStatusCode, req, res){
  6. // page available ?
  7. if (!_pages[page]){
  8. // use "internal server error" as default
  9. page = '500';
  10. httpStatusCode = null;
  11. }
  12. // set http status code
  13. res.status(httpStatusCode || 500);
  14. // extract page date
  15. const pageData = _pages[page];
  16. // multiple response formats
  17. res.format({
  18. // standard http-error-pages
  19. html: function(){
  20. res.type('.html');
  21. res.send(_renderer({
  22. code: httpStatusCode,
  23. title: pageData.title,
  24. message: pageData.message
  25. }))
  26. },
  27. // json
  28. json: function(){
  29. res.json({
  30. error: pageData.title + ' - ' + pageData.message
  31. })
  32. },
  33. // text response
  34. default: function(){
  35. // plain text
  36. res.type('.txt').send(pageData.title + ' - ' + pageData.message);
  37. }
  38. })
  39. }
  40. module.exports = dispatchRequest;