storage.ts 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import { AgentUser } from "@/features/agent/types";
  2. const AGENT_ID_KEY = "agent_user_id";
  3. const AGENT_USERNAME_KEY = "agent_username";
  4. const AGENT_ROLE_KEY = "agent_role";
  5. const isBrowser = () => typeof window !== "undefined";
  6. export function getAgentUser(): AgentUser | null {
  7. if (!isBrowser()) {
  8. return null;
  9. }
  10. const id = window.localStorage.getItem(AGENT_ID_KEY);
  11. const username = window.localStorage.getItem(AGENT_USERNAME_KEY);
  12. const role = window.localStorage.getItem(AGENT_ROLE_KEY);
  13. if (!id || !username) {
  14. return null;
  15. }
  16. const parsedId = Number.parseInt(id, 10);
  17. if (Number.isNaN(parsedId)) {
  18. return null;
  19. }
  20. return {
  21. id: parsedId,
  22. username,
  23. role: role ?? "",
  24. };
  25. }
  26. export function setAgentUser(agent: AgentUser): void {
  27. if (!isBrowser()) {
  28. return;
  29. }
  30. window.localStorage.setItem(AGENT_ID_KEY, String(agent.id));
  31. window.localStorage.setItem(AGENT_USERNAME_KEY, agent.username);
  32. window.localStorage.setItem(AGENT_ROLE_KEY, agent.role ?? "");
  33. }
  34. export function clearAgentUser(): void {
  35. if (!isBrowser()) {
  36. return;
  37. }
  38. window.localStorage.removeItem(AGENT_ID_KEY);
  39. window.localStorage.removeItem(AGENT_USERNAME_KEY);
  40. window.localStorage.removeItem(AGENT_ROLE_KEY);
  41. }