All files / services/api/profile settings.ts

94.73% Statements 18/19
100% Branches 12/12
100% Functions 3/3
94.73% Lines 18/19

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73                      18x 3x 3x       1x   2x           1x   1x                   18x 3x 3x         1x   2x             1x   1x               18x 1x 1x       1x      
import axios, { isAxiosError } from 'axios'
 
export type ChangeEmailResponse = 'OK' | 'MAIL_CONFLICT' | 'ERROR'
export type ChangePasswordResponse = 'OK' | 'UNAUTHORIZED' | 'ERROR'
export type DeleteAccountResponse = 'OK' | 'ERROR'
 
/**
 * Account settings mail change.
 * @param email new email
 * @returns Status of the request.
 */
export const changeEmail = async (email: string): Promise<ChangeEmailResponse> => {
	try {
		await axios.patch(`${process.env.NEXT_PUBLIC_API_BASE_URL}/profile/change-email`, {
			email,
		})
 
		return 'OK'
	} catch (error) {
		if (
			isAxiosError(error) &&
			error.response &&
			error.response.data.message === 'Email is already taken.' &&
			error.response.data.statusCode === 409
		) {
			return 'MAIL_CONFLICT'
		}
		return 'ERROR'
	}
}
 
/**
 * Account settings password change.
 * @param oldPassword new password
 * @param password old password
 * @returns Status of the request.
 */
export const changePassword = async (oldPassword: string, password: string) => {
	try {
		await axios.post(`${process.env.NEXT_PUBLIC_API_BASE_URL}/profile/change-password`, {
			oldPassword,
			password,
		})
 
		return 'OK'
	} catch (error) {
		if (
			isAxiosError(error) &&
			error.response &&
			error.response.data.message ===
				'This is not allowed...either you do not exist or the provided password was invalid' &&
			error.response.data.statusCode === 401
		) {
			return 'UNAUTHORIZED'
		}
		return 'ERROR'
	}
}
 
/**
 * Account settings delete account.
 * @returns Status of the request.
 */
export const deleteAccount = async () => {
	try {
		await axios.delete(`${process.env.NEXT_PUBLIC_API_BASE_URL}/profile`)
 
		return 'OK'
	} catch (error) {
		return 'ERROR'
	}
}