utils.js 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. const moment = require('moment');
  2. const path = require('path');
  3. const _ = require('lodash');
  4. const settings = require('../data/settings.json');
  5. const LOWERS = settings.titlecase.lowers;
  6. const UPPERS = settings.titlecase.uppers;
  7. const CWD = process.cwd(); // get the current working directory
  8. const LOG_LEVEL = 'low'; // should we print more information when log printing ['debug','high','medium','low']
  9. /**
  10. * get a stack error and get the details we need for logging
  11. *
  12. * @param {Object} stack Error stack.
  13. *
  14. * @return {Object} just the stuff we need for logging details;
  15. */
  16. const getStackInfo = stack => {
  17. let whodidit = stack
  18. .split('\n')[2]
  19. .trim()
  20. .substring(3)
  21. .replace(/\s\(/, ' at ')
  22. .replace(/\)/, ''); // strip out the stuff we dont care about
  23. let [caller, fileinfo] = whodidit.split(' at '); // grab the caller and fileinfo
  24. let [filename, linenumber, columnnumber] = fileinfo ? fileinfo.split(':', 3) : ['', '', '']; // get the filename line number and column number
  25. let relative = path.relative(CWD, filename); // get the relative path
  26. let name = `dc:${relative}`.replace(/.js$/, ''); // get a clean relative path name
  27. return {
  28. // return what we care about
  29. filename: filename,
  30. linenumber: linenumber,
  31. columnnumber: columnnumber,
  32. caller: caller,
  33. name: name,
  34. };
  35. };
  36. /**
  37. * get the name from the module
  38. *
  39. * @param {Object} mod module that is requireing us.
  40. *
  41. * @return {Object} just the stuff we need for logging details;
  42. */
  43. const getNameFromModule = mod => {
  44. let filename = mod && mod.parent && mod.parent.filename ? mod.parent.filename : ''; // who included me?
  45. let relative = path.relative(CWD, filename); // get the relative path
  46. let name = `dc:${relative}`.replace(/.js$/, ''); // get a clean relative path name
  47. return {
  48. // return what we care about
  49. name: name,
  50. };
  51. };
  52. /**
  53. * is a value blank?
  54. *
  55. * @param {Object} value value to check.
  56. *
  57. * @return {Boolean} result of the test.
  58. */
  59. const isBlank = value => {
  60. return (_.isEmpty(value) && !_.isNumber(value)) || _.isNaN(value);
  61. };
  62. /**
  63. * log
  64. *
  65. * @param {String} str string to print.
  66. * @param {Boolean} clearLine clear the line?.
  67. */
  68. const log = (...args) => {
  69. let { name, linenumber, columnnumber, caller } = getStackInfo(new Error().stack);
  70. let debug = require('debug')(name); // require debug
  71. let logArgs = args.slice(0); // clone args
  72. if (LOG_LEVEL && LOG_LEVEL === 'debug') {
  73. // only add stuff if we want it ... IE debug
  74. logArgs.unshift(`${linenumber}:${columnnumber}`); // add the linenumber and columnnumber
  75. logArgs.unshift(`${caller}`); // add the name
  76. }
  77. if (LOG_LEVEL && ['debug', 'high', 'medium'].indexOf(LOG_LEVEL) > -1) {
  78. logArgs.unshift(`${name} :`); // add the name
  79. logArgs.unshift(`${now()} -`); // add the timestamp
  80. }
  81. debug.apply(this, args);
  82. return console.log.apply(this, logArgs); // apply the new console.log
  83. };
  84. /**
  85. * print line
  86. *
  87. * @param {String} str string to print.
  88. * @param {Boolean} clearLine clear the line?.
  89. */
  90. const println = (str = '', clearLine = true) => {
  91. if (clearLine) {
  92. process.stdout.clearLine();
  93. process.stdout.cursorTo(0);
  94. }
  95. process.stdout.write(str);
  96. };
  97. /**
  98. * use moment to get a string version of now
  99. *
  100. * @param {Date|String|Number} seed seed the moment.
  101. *
  102. * @return {String} now formatted with DATE_TIME_FORMAT;
  103. */
  104. const now = seed => {
  105. // private now ... so we can use it locally
  106. let n = seed ? moment(seed) : moment();
  107. return n.toISOString();
  108. };
  109. /**
  110. * string to title case
  111. *
  112. * @param {String} str string to print.
  113. */
  114. const toTitleCase = (str = '') => {
  115. str = str.replace(/([^\W_]+[^\s-]*) */g, txt => txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase());
  116. for (let i = 0, j = LOWERS.length; i < j; i++) str = str.replace(new RegExp('\\s' + LOWERS[i] + '\\s', 'g'), txt => txt.toLowerCase());
  117. for (let i = 0, j = UPPERS.length; i < j; i++) str = str.replace(new RegExp('\\b' + UPPERS[i] + '\\b', 'g'), UPPERS[i].toUpperCase());
  118. return str;
  119. };
  120. module.exports = {
  121. _,
  122. after: (...args) => {
  123. return moment()
  124. .add(...args)
  125. .format(DATE_TIME_FORMAT);
  126. },
  127. before: (...args) => {
  128. return moment()
  129. .subtract(...args)
  130. .format(DATE_TIME_FORMAT);
  131. },
  132. debug: (...args) => {
  133. let { name } = getStackInfo(new Error().stack);
  134. let debug = require('debug')(name); // require debug
  135. if (LOG_LEVEL && LOG_LEVEL === 'debug') {
  136. let logArgs = args.slice(0); // clone args
  137. logArgs.unshift(`${name} :`); // add the name
  138. logArgs.unshift(`${now()} -`); // add the timestamp
  139. console.log.apply(this, logArgs); // apply the new console.log
  140. }
  141. return debug.apply(this, args); // send the orig args to debug
  142. },
  143. errorpromise: (...args) => {
  144. return Promise.reject(new Error(args));
  145. },
  146. isArray: v => {
  147. return _.isArray(v); // use lodash is array check
  148. },
  149. isBlank,
  150. isEmpty: v => {
  151. return _.isEmpty(v); // use lodash is empty check
  152. },
  153. isJson: v => {
  154. // safe check if this is json
  155. v = typeof v !== 'string' ? JSON.stringify(v) : v;
  156. try {
  157. v = JSON.parse(v);
  158. } catch (e) {
  159. return false;
  160. }
  161. return v && typeof v === 'object' && v !== null ? true : false;
  162. },
  163. later: (...args) => {
  164. return moment()
  165. .add(...args)
  166. .format(DATE_TIME_FORMAT);
  167. },
  168. log,
  169. moment: seed => {
  170. return seed ? moment(seed) : moment(); // return a new moment object ...
  171. },
  172. now, // alias the private method
  173. println,
  174. sleep: async ms => {
  175. return new Promise(resolve => setTimeout(resolve, ms));
  176. },
  177. toJson: v => {
  178. try {
  179. v = v && typeof v === 'string' ? JSON.parse(v) : v;
  180. } catch (e) {
  181. console.error('toJson error', e.message || e);
  182. return false;
  183. }
  184. return v;
  185. },
  186. toTitleCase
  187. };