index.ts 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import ms from 'ms';
  2. import {
  3. differenceInDays,
  4. differenceInHours,
  5. differenceInMonths,
  6. } from 'date-fns';
  7. export const addProtocol = (url: string): string => {
  8. const hasProtocol = /^\w+:\/\//.test(url);
  9. return hasProtocol ? url : `http://${url}`;
  10. };
  11. export const generateShortLink = (id: string, domain?: string): string => {
  12. const protocol =
  13. process.env.CUSTOM_DOMAIN_USE_HTTPS === 'true' || !domain
  14. ? 'https://'
  15. : 'http://';
  16. return `${protocol}${domain || process.env.DEFAULT_DOMAIN}/${id}`;
  17. };
  18. export const isAdmin = (email: string): boolean =>
  19. process.env.ADMIN_EMAILS.split(',')
  20. .map(e => e.trim())
  21. .includes(email);
  22. // TODO: Add statsLimit
  23. export const getStatsLimit = (): number =>
  24. Number(process.env.DEFAULT_MAX_STATS_PER_LINK) || 100000000;
  25. export const getStatsCacheTime = (total?: number): number => {
  26. let durationInMs;
  27. switch (true) {
  28. case total <= 5000:
  29. durationInMs = ms('5 minutes');
  30. break;
  31. case total > 5000 && total < 20000:
  32. durationInMs = ms('10 minutes');
  33. break;
  34. case total < 40000:
  35. durationInMs = ms('15 minutes');
  36. break;
  37. case total > 40000:
  38. durationInMs = ms('30 minutes');
  39. break;
  40. default:
  41. durationInMs = ms('5 minutes');
  42. }
  43. return durationInMs / 1000;
  44. };
  45. export const statsObjectToArray = (
  46. obj: Record<string, Record<string, number>>
  47. ) => {
  48. const objToArr = key =>
  49. Array.from(Object.keys(obj[key]))
  50. .map(name => ({
  51. name,
  52. value: obj[key][name],
  53. }))
  54. .sort((a, b) => b.value - a.value);
  55. return {
  56. browser: objToArr('browser'),
  57. os: objToArr('os'),
  58. country: objToArr('country'),
  59. referrer: objToArr('referrer'),
  60. };
  61. };
  62. export const getDifferenceFunction = (
  63. type: 'lastDay' | 'lastWeek' | 'lastMonth' | 'allTime'
  64. ): Function => {
  65. if (type === 'lastDay') return differenceInHours;
  66. if (type === 'lastWeek') return differenceInDays;
  67. if (type === 'lastMonth') return differenceInDays;
  68. if (type === 'allTime') return differenceInMonths;
  69. throw new Error('Unknown type.');
  70. };
  71. export const getUTCDate = (dateString?: Date) => {
  72. const date = new Date(dateString || Date.now());
  73. return new Date(
  74. date.getUTCFullYear(),
  75. date.getUTCMonth(),
  76. date.getUTCDate(),
  77. date.getUTCHours()
  78. );
  79. };