diff --git a/src/services/player.js b/src/services/player.js index 8b92c5bb..93b4bab7 100644 --- a/src/services/player.js +++ b/src/services/player.js @@ -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 ({ @@ -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); + } };