|
| 1 | +import { getConfig } from '../config'; |
| 2 | +import { getAuthenticatedHttpClient, getAuthenticatedUser } from '../auth'; |
| 3 | +import { convertKeyNames, snakeCaseObject } from '../utils'; |
| 4 | + |
| 5 | +interface PreferenceData { |
| 6 | + prefLang: string; |
| 7 | + [key: string]: string; |
| 8 | +} |
| 9 | + |
| 10 | +/** |
| 11 | + * Updates user language preferences via the preferences API. |
| 12 | + * |
| 13 | + * This function gets the authenticated user, converts preference data to snake_case |
| 14 | + * and formats specific keys according to backend requirements before sending the PATCH request. |
| 15 | + * If no user is authenticated, the function returns early without making the API call. |
| 16 | + * |
| 17 | + * @param {PreferenceData} preferenceData - The preference parameters to update (e.g., { prefLang: 'en' }). |
| 18 | + * @returns {Promise} - A promise that resolves when the API call completes successfully, |
| 19 | + * or rejects if there's an error with the request. Returns early if no user is authenticated. |
| 20 | + */ |
| 21 | +export async function updateAuthenticatedUserPreferences(preferenceData: PreferenceData): Promise<void> { |
| 22 | + const user = getAuthenticatedUser(); |
| 23 | + if (!user) { |
| 24 | + return Promise.resolve(); |
| 25 | + } |
| 26 | + |
| 27 | + const snakeCaseData = snakeCaseObject(preferenceData); |
| 28 | + const formattedData = convertKeyNames(snakeCaseData, { |
| 29 | + pref_lang: 'pref-lang', |
| 30 | + }); |
| 31 | + |
| 32 | + return getAuthenticatedHttpClient().patch( |
| 33 | + `${getConfig().LMS_BASE_URL}/api/user/v1/preferences/${user.username}`, |
| 34 | + formattedData, |
| 35 | + { headers: { 'Content-Type': 'application/merge-patch+json' } }, |
| 36 | + ); |
| 37 | +} |
| 38 | + |
| 39 | +/** |
| 40 | + * Sets the language for the current session using the setlang endpoint. |
| 41 | + * |
| 42 | + * This function sends a POST request to the LMS setlang endpoint to change |
| 43 | + * the language for the current user session. |
| 44 | + * |
| 45 | + * @param {string} languageCode - The language code to set (e.g., 'en', 'es', 'ar'). |
| 46 | + * Should be a valid ISO language code supported by the platform. |
| 47 | + * @returns {Promise} - A promise that resolves when the API call completes successfully, |
| 48 | + * or rejects if there's an error with the request. |
| 49 | + */ |
| 50 | +export async function setSessionLanguage(languageCode: string): Promise<void> { |
| 51 | + const formData = new FormData(); |
| 52 | + formData.append('language', languageCode); |
| 53 | + |
| 54 | + return getAuthenticatedHttpClient().post( |
| 55 | + `${getConfig().LMS_BASE_URL}/i18n/setlang/`, |
| 56 | + formData, |
| 57 | + { |
| 58 | + headers: { |
| 59 | + Accept: 'application/json', |
| 60 | + 'X-Requested-With': 'XMLHttpRequest', |
| 61 | + }, |
| 62 | + }, |
| 63 | + ); |
| 64 | +} |
0 commit comments