utils.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. 'use strict';
  2. const util = require('util');
  3. const is = require('is-type-of');
  4. const URL = require('url').URL;
  5. module.exports = {
  6. convertObject,
  7. safeParseURL,
  8. };
  9. function convertObject(obj, ignore) {
  10. if (!is.array(ignore)) ignore = [ ignore ];
  11. for (const key of Object.keys(obj)) {
  12. obj[key] = convertValue(key, obj[key], ignore);
  13. }
  14. return obj;
  15. }
  16. function convertValue(key, value, ignore) {
  17. if (is.nullOrUndefined(value)) return value;
  18. let hit;
  19. for (const matchKey of ignore) {
  20. if (is.string(matchKey) && matchKey === key) {
  21. hit = true;
  22. } else if (is.regExp(matchKey) && matchKey.test(key)) {
  23. hit = true;
  24. }
  25. }
  26. if (!hit) {
  27. if (is.symbol(value) || is.regExp(value)) return value.toString();
  28. if (is.primitive(value)) return value;
  29. if (is.array(value)) return value;
  30. }
  31. // only convert recursively when it's a plain object,
  32. // o = {}
  33. if (Object.getPrototypeOf(value) === Object.prototype) {
  34. return convertObject(value, ignore);
  35. }
  36. // support class
  37. const name = value.name || 'anonymous';
  38. if (is.class(value)) {
  39. return `<Class ${name}>`;
  40. }
  41. // support generator function
  42. if (is.function(value)) {
  43. if (is.generatorFunction(value)) return `<GeneratorFunction ${name}>`;
  44. if (is.asyncFunction(value)) return `<AsyncFunction ${name}>`;
  45. return `<Function ${name}>`;
  46. }
  47. const typeName = value.constructor.name;
  48. if (typeName) {
  49. if (is.buffer(value) || is.string(value)) return `<${typeName} len: ${value.length}>`;
  50. return `<${typeName}>`;
  51. }
  52. /* istanbul ignore next */
  53. return util.format(value);
  54. }
  55. function safeParseURL(url) {
  56. try {
  57. return new URL(url);
  58. } catch (err) {
  59. return null;
  60. }
  61. }