summaryrefslogtreecommitdiff
path: root/src/lib/api/SetPassword.ts
blob: ee445fca774706d474ced6c37cc22b6c1baa33f5 (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
46
47
48
49
50
51
52
const API_URL = process.env.NEXT_PUBLIC_API_URL;

export type SetPasswordResponse =
    | { data: { success: true }; error: null }
    | { data: null; error: { general: string } };

export const setPassword = async (
    newPassword: string,
    repeatPassword: string,
): Promise<SetPasswordResponse> => {
    try {
        const res = await fetch(`${API_URL}/api/users/password/set`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            credentials: 'include',
            body: JSON.stringify({
                new_password: newPassword,
                repeat_password: repeatPassword,
            }),
        });

        const data = await res.json().catch(() => null);

        if (!res.ok) {
            const detail = data?.detail;

            return {
                data: null,
                error: {
                    general:
                        typeof detail === 'string'
                            ? detail
                            : detail?.msg || 'Ошибка установки пароля',
                },
            };
        }

        return {
            data: { success: true },
            error: null,
        };
    } catch (err: any) {
        return {
            data: null,
            error: {
                general: err?.message || 'Network error',
            },
        };
    }
};