f4e58250e051be6d852c36099fc085a348f6855e.svn-base 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /**
  2. * Set storage
  3. *
  4. * @param name
  5. * @param content
  6. * @param maxAge
  7. */
  8. export const setStore = (name, content, maxAge = null) => {
  9. if (!global.window || !name) {
  10. return;
  11. }
  12. if (typeof content !== 'string') {
  13. content = JSON.stringify(content)
  14. }
  15. let storage = global.window.localStorage
  16. storage.setItem(name, content)
  17. if (maxAge && !isNaN(parseInt(maxAge))) {
  18. let timeout = parseInt(new Date().getTime() / 1000)
  19. storage.setItem(`${name}_expire`, timeout + maxAge)
  20. }
  21. };
  22. /**
  23. * Get storage
  24. *
  25. * @param name
  26. * @returns {*}
  27. */
  28. export const getStore = name => {
  29. if (!global.window || !name) {
  30. return;
  31. }
  32. let content = window.localStorage.getItem(name)
  33. let _expire = window.localStorage.getItem(`${name}_expire`)
  34. if (_expire) {
  35. let now = parseInt(new Date().getTime() / 1000)
  36. if (now > _expire) {
  37. return;
  38. }
  39. }
  40. try {
  41. return JSON.parse(content)
  42. } catch (e) {
  43. return content
  44. }
  45. };
  46. /**
  47. * Clear storage
  48. *
  49. * @param name
  50. */
  51. export const clearStore = name => {
  52. if (!global.window || !name) {
  53. return;
  54. }
  55. window.localStorage.removeItem(name)
  56. window.localStorage.removeItem(`${name}_expire`)
  57. };
  58. /**
  59. * Clear all storage
  60. */
  61. export const clearAll = () => {
  62. if (!global.window || !name) {
  63. return;
  64. }
  65. window.localStorage.clear()
  66. }