cookie.ts 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import { loadEnv } from "@build/utils";
  2. import { merge } from "lodash-es";
  3. import tsCookies from "typescript-cookie/dist/src/compat";
  4. class Cookies {
  5. private static env = loadEnv();
  6. constructor() {}
  7. /**
  8. * 存储 cookie 值
  9. * @param name
  10. * @param value
  11. * @param cookieSetting
  12. */
  13. set(name = "default", value = "", cookieSetting = {}) {
  14. const currentCookieSetting = {
  15. expires: 1
  16. };
  17. merge(currentCookieSetting, cookieSetting);
  18. tsCookies.set(
  19. `${Cookies.env.VITE_TITLE}-${Cookies.env.VITE_VERSION}-${name}`,
  20. value,
  21. currentCookieSetting
  22. );
  23. }
  24. /**
  25. * 拿到 cookie 值
  26. * @param name
  27. * @returns
  28. */
  29. get(name = "default") {
  30. return tsCookies.get(
  31. `${Cookies.env.VITE_TITLE}-${Cookies.env.VITE_VERSION}-${name}`
  32. );
  33. }
  34. /**
  35. * 拿到 cookie 全部的值
  36. * @returns
  37. */
  38. getAll() {
  39. return tsCookies.get();
  40. }
  41. /**
  42. * 删除 cookie
  43. * @param name
  44. */
  45. remove(name = "default") {
  46. tsCookies.remove(
  47. `${Cookies.env.VITE_TITLE}-${Cookies.env.VITE_VERSION}-${name}`
  48. );
  49. }
  50. }
  51. export const cookies = new Cookies();