user.ts 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import { StorageEnum } from '../base/enums';
  2. import { createStorage } from '../base/base';
  3. import type { BaseStorage } from '../base/types';
  4. // Interface for user profile configuration
  5. export interface UserProfile {
  6. userId: string;
  7. }
  8. export type UserStorage = BaseStorage<UserProfile> & {
  9. createProfile: (profile: Partial<UserProfile>) => Promise<void>;
  10. updateProfile: (profile: Partial<UserProfile>) => Promise<void>;
  11. getProfile: () => Promise<UserProfile>;
  12. getUserId: () => Promise<string>;
  13. };
  14. // Default profile
  15. export const DEFAULT_USER_PROFILE: UserProfile = {
  16. userId: 'unknown',
  17. };
  18. const storage = createStorage<UserProfile>('user-profile', DEFAULT_USER_PROFILE, {
  19. storageEnum: StorageEnum.Local,
  20. liveUpdate: true,
  21. });
  22. export const userStore: UserStorage = {
  23. ...storage,
  24. async createProfile(profile: Partial<UserProfile>) {
  25. const fullProfile = {
  26. ...DEFAULT_USER_PROFILE,
  27. ...profile,
  28. };
  29. await storage.set(fullProfile);
  30. },
  31. async updateProfile(profile: Partial<UserProfile>) {
  32. const currentProfile = (await storage.get()) || DEFAULT_USER_PROFILE;
  33. await storage.set({
  34. ...currentProfile,
  35. ...profile,
  36. });
  37. },
  38. async getProfile() {
  39. const profile = await storage.get();
  40. return profile || DEFAULT_USER_PROFILE;
  41. },
  42. async getUserId() {
  43. const profile = await this.getProfile();
  44. if (!profile.userId) {
  45. const newUserId = crypto.randomUUID();
  46. await this.updateProfile({ userId: newUserId });
  47. return newUserId;
  48. }
  49. return profile.userId;
  50. },
  51. };