Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
92 changes: 68 additions & 24 deletions src/services/player.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,27 @@ export const normalizeRatingForApi = (value) => {
}

const rounded = Math.round(numeric * 10) / 10;
return rounded.toFixed(1);
return rounded;
};

const formatRatingValue = (value, { asString = false } = {}) => {
if (value === undefined) {
return undefined;
}

if (value === null) {
return null;
}

if (!Number.isFinite(value)) {
return undefined;
}

if (!asString) {
return value;
}

return value.toFixed(1);
};

export const updatePlayerPersonalDetails = async ({
Expand All @@ -46,30 +66,54 @@ export const updatePlayerPersonalDetails = async ({
const normalizedUstaRating = normalizeRatingForApi(usta_rating);
const normalizedUtaRating = normalizeRatingForApi(uta_rating);

const params = Object.entries({
id,
date_of_birth,
usta_rating: normalizedUstaRating,
uta_rating: normalizedUtaRating,
full_name: fullName,
phone: mobile,
about_me,
profile_picture,
}).reduce((acc, [key, value]) => {
if (value !== undefined) {
acc[key] = value;
}
return acc;
}, {});
const buildParams = ({ ratingsAsString = false } = {}) =>
Object.entries({
id,
date_of_birth,
usta_rating: ratingsAsString
? formatRatingValue(normalizedUstaRating, { asString: true })
: normalizedUstaRating,
uta_rating: ratingsAsString
? formatRatingValue(normalizedUtaRating, { asString: true })
: normalizedUtaRating,
full_name: fullName,
phone: mobile,
about_me,
profile_picture,
}).reduce((acc, [key, value]) => {
if (value !== undefined) {
acc[key] = value;
}
return acc;
}, {});

const params = buildParams();

const method = id ? "PATCH" : "POST";

return unwrap(
api(`/player/personal_details`, {
method,
authToken: authHeader,
authSchemePreference: "token",
json: params,
}),
);
const send = (body) =>
unwrap(
api(`/player/personal_details`, {
method,
authToken: authHeader,
authSchemePreference: "token",
json: body,
}),
);

try {
return await send(params);
} catch (error) {
const status = Number(error?.status ?? error?.response?.status);
const hasNumericRatings = [normalizedUstaRating, normalizedUtaRating].some(
(value) => typeof value === "number" && Number.isFinite(value),
);

if (status !== 422 || !hasNumericRatings) {
throw error;
}

const fallbackParams = buildParams({ ratingsAsString: true });
return send(fallbackParams);
}
};