decorateWithLogger.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. Object.defineProperty(exports, "__esModule", { value: true });
  2. var graphql_1 = require("graphql");
  3. /*
  4. * fn: The function to decorate with the logger
  5. * logger: an object instance of type Logger
  6. * hint: an optional hint to add to the error's message
  7. */
  8. function decorateWithLogger(fn, logger, hint) {
  9. if (typeof fn === 'undefined') {
  10. fn = graphql_1.defaultFieldResolver;
  11. }
  12. var logError = function (e) {
  13. // TODO: clone the error properly
  14. var newE = new Error();
  15. newE.stack = e.stack;
  16. /* istanbul ignore else: always get the hint from addErrorLoggingToSchema */
  17. if (hint) {
  18. newE['originalMessage'] = e.message;
  19. newE['message'] = "Error in resolver " + hint + "\n" + e.message;
  20. }
  21. logger.log(newE);
  22. };
  23. return function (root, args, ctx, info) {
  24. try {
  25. var result = fn(root, args, ctx, info);
  26. // If the resolve function returns a Promise log any Promise rejects.
  27. if (result &&
  28. typeof result.then === 'function' &&
  29. typeof result.catch === 'function') {
  30. result.catch(function (reason) {
  31. // make sure that it's an error we're logging.
  32. var error = reason instanceof Error ? reason : new Error(reason);
  33. logError(error);
  34. // We don't want to leave an unhandled exception so pass on error.
  35. return reason;
  36. });
  37. }
  38. return result;
  39. }
  40. catch (e) {
  41. logError(e);
  42. // we want to pass on the error, just in case.
  43. throw e;
  44. }
  45. };
  46. }
  47. exports.default = decorateWithLogger;
  48. //# sourceMappingURL=decorateWithLogger.js.map