utils.ts 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import { formatDate } from '@vueuse/shared'
  2. export const isNullOrBlank = (string: string | null | undefined | number) =>
  3. string == null ||
  4. (string as string).length === 0 ||
  5. /^\s+$/.test(string as string)
  6. export const isLegadoUrl = (/** @type {string} */ url: string) =>
  7. /,\s*\{/.test(url) ||
  8. !(
  9. url.startsWith('http') ||
  10. url.startsWith('data:') ||
  11. url.startsWith('blob:')
  12. )
  13. /**
  14. * 验证输入的URL是否符合阅读后端地址规则
  15. * @param allowedProtocols 允许的协议,默认`["https:", "http:"]`
  16. */
  17. export const validatorHttpUrl = (
  18. http_url: string | URL,
  19. allowedProtocols: string[] = ['https:', 'http:'],
  20. ) => {
  21. try {
  22. const url = new URL(http_url)
  23. const { protocol } = url
  24. if (!allowedProtocols.includes(protocol))
  25. throw new Error(
  26. `Expected protocol ${allowedProtocols.join('/')}, but ${protocol}`,
  27. )
  28. return true
  29. } catch {
  30. return false
  31. }
  32. }
  33. export const dateFormat = (/** @type {number} */ t: number) => {
  34. const time = new Date().getTime()
  35. const offset = Math.floor((time - t) / 1000)
  36. let str = ''
  37. if (offset <= 30) {
  38. str = '刚刚'
  39. } else if (offset < 60) {
  40. str = offset + '秒前'
  41. } else if (offset < 3600) {
  42. str = Math.floor(offset / 60) + '分钟前'
  43. } else if (offset < 86400) {
  44. str = Math.floor(offset / 3600) + '小时前'
  45. } else if (offset < 2592000) {
  46. str = Math.floor(offset / 86400) + '天前'
  47. } else {
  48. str = formatDate(new Date(t), 'YYYY-MM-DD')
  49. }
  50. return str
  51. }