format.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. 'use strict';
  2. /*
  3. * Displays a helpful message and the source of
  4. * the format when it is invalid.
  5. */
  6. class InvalidFormatError extends Error {
  7. constructor(formatFn) {
  8. super(`Format functions must be synchronous taking a two arguments: (info, opts)
  9. Found: ${formatFn.toString().split('\n')[0]}\n`);
  10. Error.captureStackTrace(this, InvalidFormatError);
  11. }
  12. }
  13. /*
  14. * function format (formatFn)
  15. * Returns a create function for the `formatFn`.
  16. */
  17. module.exports = formatFn => {
  18. if (formatFn.length > 2) {
  19. throw new InvalidFormatError(formatFn);
  20. }
  21. /*
  22. * function Format (options)
  23. * Base prototype which calls a `_format`
  24. * function and pushes the result.
  25. */
  26. function Format(options = {}) {
  27. this.options = options;
  28. }
  29. Format.prototype.transform = formatFn;
  30. //
  31. // Create a function which returns new instances of
  32. // FormatWrap for simple syntax like:
  33. //
  34. // require('winston').formats.json();
  35. //
  36. function createFormatWrap(opts) {
  37. return new Format(opts);
  38. }
  39. //
  40. // Expose the FormatWrap through the create function
  41. // for testability.
  42. //
  43. createFormatWrap.Format = Format;
  44. return createFormatWrap;
  45. };