format.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. 'use strict';
  2. /*
  3. * Displays a helpful message and the source of
  4. * the format when it is invalid.
  5. */
  6. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  7. function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
  8. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  9. var InvalidFormatError = function (_Error) {
  10. _inherits(InvalidFormatError, _Error);
  11. function InvalidFormatError(formatFn) {
  12. _classCallCheck(this, InvalidFormatError);
  13. var _this = _possibleConstructorReturn(this, (InvalidFormatError.__proto__ || Object.getPrototypeOf(InvalidFormatError)).call(this, 'Format functions must be synchronous taking a two arguments: (info, opts)\nFound: ' + formatFn.toString().split('\n')[0] + '\n'));
  14. Error.captureStackTrace(_this, InvalidFormatError);
  15. return _this;
  16. }
  17. return InvalidFormatError;
  18. }(Error);
  19. /*
  20. * function format (formatFn)
  21. * Returns a create function for the `formatFn`.
  22. */
  23. module.exports = function (formatFn) {
  24. if (formatFn.length > 2) {
  25. throw new InvalidFormatError(formatFn);
  26. }
  27. /*
  28. * function Format (options)
  29. * Base prototype which calls a `_format`
  30. * function and pushes the result.
  31. */
  32. function Format() {
  33. var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  34. this.options = options;
  35. }
  36. Format.prototype.transform = formatFn;
  37. //
  38. // Create a function which returns new instances of
  39. // FormatWrap for simple syntax like:
  40. //
  41. // require('winston').formats.json();
  42. //
  43. function createFormatWrap(opts) {
  44. return new Format(opts);
  45. }
  46. //
  47. // Expose the FormatWrap through the create function
  48. // for testability.
  49. //
  50. createFormatWrap.Format = Format;
  51. return createFormatWrap;
  52. };