koa.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. const _render = require('./page-renderer');
  2. const _parseOptions = require('./options');
  3. const _getResources = require('./resources');
  4. const _dispatch = require('./dispatcher');
  5. // wrapper to add custom options
  6. async function createDispatcher(options={}){
  7. // merge options
  8. const opt = _parseOptions(options);
  9. // load resources
  10. const resources = await _getResources(opt);
  11. // multi-type support
  12. // @see https://github.com/koajs/koa/blob/master/docs/api/response.md#responseistypes
  13. return function dispatchRequest(page, httpStatusCode, ctx, err){
  14. // run generic dispatcher
  15. const {pageData, templateVars} = _dispatch(opt, resources, page, httpStatusCode, err);
  16. // set http status code
  17. ctx.status = httpStatusCode || 500;
  18. // multiple response formats
  19. switch (ctx.accepts('json', 'html', 'text')){
  20. // jsonn response
  21. case 'json':
  22. ctx.type = 'json';
  23. ctx.body = {
  24. error: `${pageData.title} - ${pageData.message}`
  25. }
  26. break;
  27. // html response
  28. case 'html':
  29. ctx.type = 'html';
  30. ctx.body = _render(resources.template, resources.stylesheet, opt.filter(templateVars, ctx));
  31. break;
  32. // default: text response
  33. default:
  34. ctx.type = 'text/plain';
  35. ctx.body = `${pageData.title} - ${pageData.message}`;
  36. }
  37. }
  38. }
  39. module.exports = async function httpErrorPages(options={}){
  40. // create new disptacher with given options
  41. const dispatch = await createDispatcher(options);
  42. // create error handler
  43. // @see https://github.com/koajs/koa/blob/master/docs/error-handling.md
  44. return async (ctx, next) => {
  45. try{
  46. // dispatch middleware chain
  47. await next();
  48. // route not found ?
  49. if (ctx.status === 404) {
  50. dispatch('404', 404, ctx, new Error('file not found'));
  51. }
  52. }catch(err){
  53. // status code given ?
  54. if (err.status){
  55. // custom errorpage set ?
  56. dispatch(err.errorpage || err.status, err.status, ctx, err);
  57. // use default http500 page
  58. }else{
  59. dispatch('500', 500, ctx, err);
  60. }
  61. }
  62. }
  63. }