utils.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  1. const {
  2. isEmpty: _isEmpty,
  3. isEqual: _isEqual,
  4. isNaN: _isNaN,
  5. isNumber: _isNumber,
  6. merge,
  7. omit,
  8. omitBy,
  9. parseInt: _parseInt,
  10. pick
  11. } = require("lodash");
  12. const fetcher = (url) => fetch(url).then((res) => res.json());
  13. const parse = (value) => {
  14. try {
  15. return JSON.parse(value);
  16. } catch (_) {
  17. return value;
  18. }
  19. };
  20. const stringify = (value, opts) => {
  21. try {
  22. return opts ? JSON.stringify(value, null, opts) : JSON.stringify(value);
  23. } catch (_) {
  24. return value;
  25. }
  26. };
  27. const btoa = (value, options = {}) => {
  28. const { urlsafe = true } = options;
  29. let result = Buffer.from(value, "binary").toString("base64");
  30. if (urlsafe)
  31. result = result.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
  32. return result;
  33. };
  34. const atob = (value, options = {}) => {
  35. const { urlsafe = true } = options;
  36. if (urlsafe) value = value.replace(/-/g, "+").replace(/_/g, "/");
  37. if (urlsafe && value && value.toString().length % 4 !== 0)
  38. value += "===".slice(0, 4 - (value.toString().length % 4));
  39. let result = Buffer.from(value, "base64").toString("binary");
  40. return result.toString();
  41. };
  42. const querystring = (params = {}, options = {}) => {
  43. if (!isObject(params)) return;
  44. const { exclude = [], compress = false } = options;
  45. const encodeAndCompress = (param) => {
  46. const json = stringify(param);
  47. return compress ? pako.deflate(json, { to: "string" }) : json;
  48. // return compress ? encodeURI(pako.deflate(json, { to: "string" })) : encodeURI(json);
  49. };
  50. const props = {};
  51. for (let key of Object.keys(params)) {
  52. props[key] = isObject(params[key])
  53. ? encodeAndCompress(params[key])
  54. : params[key];
  55. }
  56. return new URLSearchParams(omit(props, exclude)).toString();
  57. };
  58. const safeEncodeURIComponent = (v) => {
  59. v = parse(v); // try to parse the value
  60. try {
  61. if (v && (Array.isArray(v) || isObject(v))) v = stringify(v); // is it an array? or object? stringify
  62. } catch (err) {
  63. // do nothing use valu v
  64. }
  65. try {
  66. return encodeURIComponent(v); // encodeURIComponent the value and resurn it
  67. } catch (err) {
  68. return v; // fail and return v
  69. }
  70. };
  71. const language = () => {
  72. return (
  73. (navigator.languages && navigator.languages[0]) ||
  74. navigator.language ||
  75. navigator.userLanguage
  76. );
  77. };
  78. const uuid = () => Math.random().toString(36).substr(2, 9);
  79. const uniqueId = (x = 4, j = "-") =>
  80. [...Array(x).keys()].map(() => uuid()).join(j);
  81. const normalizeUrl = (url) => {
  82. let pattern = /^((http|https|ftp):\/\/)/;
  83. if (url && url !== "") {
  84. url = url.toString();
  85. if (!pattern.test(url) && !url.startsWith("/")) url = "http://" + url;
  86. }
  87. return url;
  88. };
  89. const normalizeJSON = (value, fallback = null) => {
  90. if (isString(value)) return parse(value) || fallback;
  91. else if (isObject(value)) return value || fallback;
  92. else return fallback;
  93. };
  94. const safeSearchName = (text = "") =>
  95. encodeURIComponent(text || "")
  96. .toString()
  97. .trim()
  98. .replace(/%20/g, "+");
  99. const kebabCase = (text = "") =>
  100. (text || "")
  101. .toString() // convert to string to avoid issues
  102. .replace(/\s+/, "-") // spaces to dash
  103. .replace(/([a-z])([A-Z])/g, "$1-$2") // kebab the string
  104. .replace(/[\s_]+/g, "-")
  105. .replace(/-+/g, "-") // only one dash per kebab
  106. .replace(/^-/g, "") // no starting dash
  107. .replace(/-$/g, "") // no ending dash
  108. .replace(/[^0-9a-z-_]/gi, "") // only alpha numeric
  109. .toLowerCase(); // lowercase only
  110. const safeIdName = (text = "") =>
  111. kebabCase((text || "").toString().replace(/\s\s+/g, " "));
  112. const slugify = (text = "") => kebabCase(text || "");
  113. const baseUrl = (path) => {
  114. if (!hasWindow()) return `${BASE_URL}${path}`;
  115. const { location: { origin } = {} } = window;
  116. return `${origin || BASE_URL}${path || ""}`;
  117. };
  118. const toBoolean = (value) => {
  119. switch (value) {
  120. case true:
  121. case "true":
  122. case "True":
  123. case "TRUE":
  124. case 1:
  125. case "1":
  126. case "on":
  127. case "On":
  128. case "ON":
  129. case "yes":
  130. case "Yes":
  131. case "YES":
  132. return true;
  133. default:
  134. return false;
  135. }
  136. };
  137. const isBlank = (value) =>
  138. (_isEmpty(value) && !_isNumber(value)) || _isNaN(value);
  139. const isEqual = (v1, v2) => _isEqual(v1, v2);
  140. const isEmpty = (value) => {
  141. let result,
  142. type = typeof value;
  143. switch (type.toLowerCase()) {
  144. case "null":
  145. case "undefined":
  146. result = true;
  147. break;
  148. case "boolean":
  149. case "number":
  150. case "bigint":
  151. result = value === undefined || value === null ? true : false;
  152. break;
  153. case "symbol":
  154. case "object":
  155. try {
  156. if (typeofDate(value)) {
  157. result = false;
  158. } else if (isArray(value)) {
  159. result = !value || value.length === 0 ? true : false;
  160. } else if (value) {
  161. let entries = Object.entries(value);
  162. result = !entries || entries.length === 0 ? true : false;
  163. } else {
  164. result = true;
  165. }
  166. } catch (err) {
  167. log.error("isEmpty", type, err.message || err);
  168. result = true;
  169. }
  170. break;
  171. case "date":
  172. result = false;
  173. break;
  174. case "string":
  175. default:
  176. result =
  177. !value || value.trim() === "" || value === undefined || value === null
  178. ? true
  179. : false;
  180. break;
  181. }
  182. return result;
  183. };
  184. const isFunction = (o) => {
  185. return o && typeof o === "function" ? true : false;
  186. };
  187. const isJson = (o) => {
  188. return isArray(o) || isObject(o) ? true : hasJsonStructure(o);
  189. };
  190. const isReactElement = (o) => {
  191. return o?.["$$typeof"] && o["$$typeof"] === Symbol.for("react.element");
  192. };
  193. const hasJsonStructure = (o) => {
  194. if (typeof o !== "string") return false;
  195. try {
  196. const result = JSON.parse(o);
  197. const type = Object.prototype.toString.call(result);
  198. return type === "[object Object]" || type === "[object Array]";
  199. } catch (err) {
  200. return false;
  201. }
  202. };
  203. const isString = (o) => {
  204. return o && typeof o === "string" ? true : false;
  205. };
  206. const isArray = (o) => {
  207. return o && Array.isArray(o) ? true : false;
  208. };
  209. const isObject = (o) => {
  210. return o && typeof o === "object" ? true : false;
  211. };
  212. const isUndefined = (o) => {
  213. return typeof o === "undefined" ? true : false;
  214. };
  215. const hasWindow = () => {
  216. return typeof window !== "undefined" && window ? true : false;
  217. };
  218. const hasNavigator = () => {
  219. return typeof navigator !== "undefined" && navigator ? true : false;
  220. };
  221. const hasDocument = () => {
  222. return typeof document !== "undefined" && document ? true : false;
  223. };
  224. const typeofDate = (value) => {
  225. return (
  226. value &&
  227. Object.prototype.toString.call(value) === "[object Date]" &&
  228. !isNaN(value)
  229. );
  230. };
  231. const isDate = (value) => {
  232. const regex = /^\d{1,2}\/\d{1,2}\/\d{4}$/;
  233. return value && regex.test(value) ? true : false;
  234. };
  235. const isHex = (h) => {
  236. try {
  237. return /^#[0-9A-F]{6}$/i.test(h);
  238. } catch (err) {
  239. return false;
  240. }
  241. };
  242. const isNullOrFalse = (value) => {
  243. return value === null || value === undefined || value === false
  244. ? true
  245. : false;
  246. };
  247. const isNullOrZero = (value) => {
  248. return value === null || value === undefined || value == 0 ? true : false;
  249. };
  250. const formatCurrency = (
  251. value,
  252. formatter = new Intl.NumberFormat("en-US", {
  253. style: "currency",
  254. currency: "USD"
  255. })
  256. ) => {
  257. return (formatter && value && formatter.format(value)) || 0;
  258. };
  259. const isInt = (value) => {
  260. if (value === null || value === undefined || value === "") return false;
  261. return /^-?[0-9]+$/.test(value);
  262. };
  263. const isNumber = (value) => {
  264. return value % 1 === 0 ? true : false;
  265. };
  266. const isUrl = (value) => {
  267. let url;
  268. try {
  269. url = new URL(value);
  270. } catch (_) {
  271. return false;
  272. }
  273. return (
  274. url &&
  275. url.protocol &&
  276. ["http:", "https:", "ftp:", "ftps:"].includes(url.protocol)
  277. );
  278. };
  279. const clone = (obj = {}) => {
  280. let result = {};
  281. try {
  282. result = JSON.parse(JSON.stringify(obj));
  283. } catch (err) {
  284. log.error("clone error", err.message || err);
  285. }
  286. return result;
  287. };
  288. const isValidUrl = (str) => {
  289. let url;
  290. try {
  291. url = new URL(str);
  292. } catch (_) {
  293. return false;
  294. }
  295. return url.protocol === "http:" || url.protocol === "https:";
  296. };
  297. const asyncSome = async (arr, predicate) => {
  298. for (let a of arr) {
  299. if (await predicate(a)) return true;
  300. }
  301. return false;
  302. };
  303. const asyncEvery = async (arr, predicate) => {
  304. for (let a of arr) {
  305. if (!(await predicate(a))) return false;
  306. }
  307. return true;
  308. };
  309. const objectToString = (value, delim = ",") => {
  310. try {
  311. if (!value) return null;
  312. if (isString(value)) return value;
  313. else if (isArray(value)) return value.join(delim);
  314. else return stringify(value, null, 2);
  315. } catch (err) {
  316. return null;
  317. }
  318. };
  319. const stringToArray = (value, delim = ",", clean = true) => {
  320. if (!value) return [];
  321. if (value && Array.isArray(value)) return value;
  322. let result = [];
  323. try {
  324. result = (value && value.toString().split(delim)) || [];
  325. if (clean)
  326. result =
  327. (result &&
  328. result.map((v) => v.trim()).filter((v) => v && !isEmpty(v))) ||
  329. [];
  330. } catch (err) {
  331. result = [];
  332. }
  333. return result;
  334. };
  335. const stringToObject = (value, delim = ",", clean = true) => {
  336. try {
  337. // if (!value) return {};
  338. if (isObject(value)) return value;
  339. else if (value.includes("[") && value.includes("]")) return parse(value);
  340. else if (value.includes("{") && value.includes("}")) return parse(value);
  341. else {
  342. if (clean) value = stripNewlines(value, delim) || "";
  343. return (
  344. value &&
  345. value
  346. .toString()
  347. .split(delim)
  348. .map((v) => v.trim())
  349. .filter((v) => !isEmpty(v))
  350. );
  351. }
  352. } catch (err) {
  353. return {};
  354. }
  355. };
  356. const stripNewlines = (value, subs = "") => {
  357. if (!value) return;
  358. let result;
  359. try {
  360. result = value.toString().replace(/(\r\n|\r|\n)/g, subs);
  361. } catch (err) {
  362. // do nothing
  363. }
  364. return result;
  365. };
  366. const capitalizeFirstLetter = (s) => s.charAt(0).toUpperCase() + s.slice(1);
  367. const reload = () => {
  368. if (hasWindow() && window.location) window.location.reload(false);
  369. };
  370. const hasOwnProperty = (obj, key) => {
  371. return obj && key && Object.prototype.hasOwnProperty.call(obj, key);
  372. };
  373. const hasKey = (needle = "", haystack = {}) => {
  374. if (!needle || isEmpty(haystack)) return false;
  375. let keys = Object.keys(haystack) || [];
  376. return needle instanceof RegExp
  377. ? keys.some((o) => o && needle.test(o))
  378. : keys.some((o) => o && ciEquals(needle, o));
  379. };
  380. const isIterable = (obj) => {
  381. if (obj) return typeof obj[Symbol.iterator] === "function";
  382. return false;
  383. };
  384. const hasHtml = (value) => value && /<\/?[^>]*>/.test(value);
  385. const firstOfList = (value) => (isArray(value) ? value[0] : value);
  386. const truncateArray = (list = [], max = 7) => {
  387. if (list.length < max) return list;
  388. return [...list.slice(0, max), "..."];
  389. };
  390. module.exports = {
  391. atob,
  392. baseUrl,
  393. btoa,
  394. capitalizeFirstLetter,
  395. clone,
  396. fetcher,
  397. firstOfList,
  398. formatCurrency,
  399. hasDocument,
  400. hasJsonStructure,
  401. hasHtml,
  402. hasKey,
  403. hasNavigator,
  404. hasOwnProperty,
  405. hasWindow,
  406. isArray,
  407. isBlank,
  408. isDate,
  409. isEqual,
  410. isEmpty,
  411. isFunction,
  412. isHex,
  413. isInt,
  414. isIterable,
  415. isJson,
  416. isNumber,
  417. isNullOrFalse,
  418. isNullOrZero,
  419. isObject,
  420. isReactElement,
  421. isValidUrl,
  422. isUrl,
  423. isUndefined,
  424. isString,
  425. language,
  426. merge,
  427. normalizeUrl,
  428. normalizeJSON,
  429. objectToString,
  430. omit,
  431. omitBy,
  432. parse,
  433. pick,
  434. querystring,
  435. reload,
  436. safeIdName,
  437. safeEncodeURIComponent,
  438. safeSearchName,
  439. slugify,
  440. stringify,
  441. stringToArray,
  442. stringToObject,
  443. stripNewlines,
  444. toBoolean,
  445. truncateArray,
  446. typeofDate,
  447. uuid,
  448. uniqueId
  449. };