helpers.js 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.toString = exports.paginate = exports.limitArrayLength = exports.generateRandomColor = exports.formatBytes = exports.isValidMqttTopic = exports.isValidIpAddress = exports.retry = exports.sleep = exports.deepClone = exports.generateId = exports.getDateMinutesAgo = exports.getDateHoursAgo = exports.getDateDaysAgo = exports.getTimeDifferenceInDays = exports.getTimeDifferenceInHours = exports.getTimeDifferenceInMinutes = exports.getTimeDifferenceInSeconds = exports.getCurrentDateTime = exports.getCurrentTimestamp = exports.formatTimestamp = exports.formatDateTime = exports.formatDate = void 0;
  4. const formatDate = (date) => {
  5. const d = new Date(date);
  6. return d.toISOString().split('T')[0];
  7. };
  8. exports.formatDate = formatDate;
  9. const formatDateTime = (date) => {
  10. const d = new Date(date);
  11. return d.toISOString();
  12. };
  13. exports.formatDateTime = formatDateTime;
  14. const formatTimestamp = (timestamp) => {
  15. return new Date(timestamp).toISOString();
  16. };
  17. exports.formatTimestamp = formatTimestamp;
  18. const getCurrentTimestamp = () => {
  19. return Date.now();
  20. };
  21. exports.getCurrentTimestamp = getCurrentTimestamp;
  22. const getCurrentDateTime = () => {
  23. return new Date().toISOString();
  24. };
  25. exports.getCurrentDateTime = getCurrentDateTime;
  26. const getTimeDifferenceInSeconds = (date1, date2) => {
  27. const d1 = new Date(date1);
  28. const d2 = new Date(date2);
  29. return Math.abs((d1.getTime() - d2.getTime()) / 1000);
  30. };
  31. exports.getTimeDifferenceInSeconds = getTimeDifferenceInSeconds;
  32. const getTimeDifferenceInMinutes = (date1, date2) => {
  33. return (0, exports.getTimeDifferenceInSeconds)(date1, date2) / 60;
  34. };
  35. exports.getTimeDifferenceInMinutes = getTimeDifferenceInMinutes;
  36. const getTimeDifferenceInHours = (date1, date2) => {
  37. return (0, exports.getTimeDifferenceInMinutes)(date1, date2) / 60;
  38. };
  39. exports.getTimeDifferenceInHours = getTimeDifferenceInHours;
  40. const getTimeDifferenceInDays = (date1, date2) => {
  41. return (0, exports.getTimeDifferenceInHours)(date1, date2) / 24;
  42. };
  43. exports.getTimeDifferenceInDays = getTimeDifferenceInDays;
  44. const getDateDaysAgo = (days) => {
  45. const date = new Date();
  46. date.setDate(date.getDate() - days);
  47. return date;
  48. };
  49. exports.getDateDaysAgo = getDateDaysAgo;
  50. const getDateHoursAgo = (hours) => {
  51. const date = new Date();
  52. date.setHours(date.getHours() - hours);
  53. return date;
  54. };
  55. exports.getDateHoursAgo = getDateHoursAgo;
  56. const getDateMinutesAgo = (minutes) => {
  57. const date = new Date();
  58. date.setMinutes(date.getMinutes() - minutes);
  59. return date;
  60. };
  61. exports.getDateMinutesAgo = getDateMinutesAgo;
  62. const generateId = () => {
  63. return Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
  64. };
  65. exports.generateId = generateId;
  66. const deepClone = (obj) => {
  67. if (obj === null || typeof obj !== 'object') {
  68. return obj;
  69. }
  70. if (obj instanceof Date) {
  71. return new Date(obj.getTime());
  72. }
  73. if (obj instanceof Array) {
  74. return obj.map(item => (0, exports.deepClone)(item));
  75. }
  76. if (typeof obj === 'object') {
  77. const clonedObj = {};
  78. for (const key in obj) {
  79. if (obj.hasOwnProperty(key)) {
  80. clonedObj[key] = (0, exports.deepClone)(obj[key]);
  81. }
  82. }
  83. return clonedObj;
  84. }
  85. return obj;
  86. };
  87. exports.deepClone = deepClone;
  88. const sleep = (ms) => {
  89. return new Promise(resolve => setTimeout(resolve, ms));
  90. };
  91. exports.sleep = sleep;
  92. const retry = async (fn, maxAttempts = 3, delayMs = 1000) => {
  93. let lastError;
  94. for (let attempt = 1; attempt <= maxAttempts; attempt++) {
  95. try {
  96. return await fn();
  97. }
  98. catch (error) {
  99. lastError = error;
  100. console.error(`尝试 ${attempt}/${maxAttempts} 失败:`, error);
  101. if (attempt < maxAttempts) {
  102. console.log(`${delayMs}ms后重试...`);
  103. await (0, exports.sleep)(delayMs);
  104. }
  105. }
  106. }
  107. throw lastError;
  108. };
  109. exports.retry = retry;
  110. const isValidIpAddress = (ip) => {
  111. const ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
  112. return ipv4Regex.test(ip);
  113. };
  114. exports.isValidIpAddress = isValidIpAddress;
  115. const isValidMqttTopic = (topic) => {
  116. if (!topic || topic.length > 65535) {
  117. return false;
  118. }
  119. const hasWildcards = topic.includes('#') || topic.includes('+');
  120. if (hasWildcards) {
  121. if (topic.includes('#') && topic.lastIndexOf('#') !== topic.length - 1) {
  122. return false;
  123. }
  124. const parts = topic.split('/');
  125. for (const part of parts) {
  126. if (part === '+') {
  127. continue;
  128. }
  129. if (part.includes('+')) {
  130. return false;
  131. }
  132. }
  133. }
  134. return true;
  135. };
  136. exports.isValidMqttTopic = isValidMqttTopic;
  137. const formatBytes = (bytes, decimals = 2) => {
  138. if (bytes === 0)
  139. return '0 Bytes';
  140. const k = 1024;
  141. const dm = decimals < 0 ? 0 : decimals;
  142. const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  143. const i = Math.floor(Math.log(bytes) / Math.log(k));
  144. return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
  145. };
  146. exports.formatBytes = formatBytes;
  147. const generateRandomColor = () => {
  148. return '#' + Math.floor(Math.random() * 16777215).toString(16);
  149. };
  150. exports.generateRandomColor = generateRandomColor;
  151. const limitArrayLength = (array, maxLength) => {
  152. return array.length > maxLength ? array.slice(0, maxLength) : array;
  153. };
  154. exports.limitArrayLength = limitArrayLength;
  155. const paginate = (items, page = 1, pageSize = 10) => {
  156. const totalPages = Math.ceil(items.length / pageSize);
  157. const currentPage = Math.max(1, Math.min(page, totalPages));
  158. const startIndex = (currentPage - 1) * pageSize;
  159. const endIndex = startIndex + pageSize;
  160. return {
  161. items: items.slice(startIndex, endIndex),
  162. totalPages,
  163. currentPage,
  164. hasNext: currentPage < totalPages,
  165. hasPrev: currentPage > 1
  166. };
  167. };
  168. exports.paginate = paginate;
  169. const toString = (value) => {
  170. if (Array.isArray(value)) {
  171. const first = value[0];
  172. if (typeof first === 'string') {
  173. return first;
  174. }
  175. return String(first || '');
  176. }
  177. if (typeof value === 'string') {
  178. return value;
  179. }
  180. return String(value || '');
  181. };
  182. exports.toString = toString;
  183. //# sourceMappingURL=helpers.js.map