summaryrefslogtreecommitdiffstats
path: root/src/features/profile/services/profileService.ts
blob: 566c3fa2bc6a23c0be3778424d3c785332fabb02 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// src/features/profile/services/profileService.ts

import { doc, getDoc, updateDoc } from 'firebase/firestore';
import { updateProfile } from 'firebase/auth';
import { db, auth } from '@/shared/lib/firebase/config';
import { UserProfile } from '@/features/profile/types';

export const profileService = {
  async getMyProfile(uid: string): Promise<UserProfile | null> {
    const snapshot = await getDoc(doc(db, 'users', uid));

    if (!snapshot.exists()) {
      return null;
    }

    const data = snapshot.data();

    return {
      uid,
      email: data.email ?? '',
      displayName: data.displayName ?? '',
      photoURL: data.photoURL ?? '',
    };
  },

  async updateMyProfile(params: {
    uid: string;
    displayName: string;
    photoURL?: string;
  }): Promise<void> {
    const { uid, displayName, photoURL } = params;

    await updateDoc(doc(db, 'users', uid), {
      displayName,
      ...(photoURL !== undefined ? { photoURL } : {}),
    });

    if (auth.currentUser) {
      await updateProfile(auth.currentUser, {
        displayName,
        ...(photoURL !== undefined ? { photoURL } : {}),
      });
    }
  },
};