Try not to mutate

This commit is contained in:
Eric Bailey
2024-09-17 09:33:19 -05:00
parent e65bbd4ebf
commit bc46ae65df
+18 -15
View File
@@ -4,39 +4,42 @@ import {logger} from '#/logger'
import {Schema} from '#/state/persisted/schema' import {Schema} from '#/state/persisted/schema'
export function normalizeData(data: Schema) { export function normalizeData(data: Schema) {
const next = {...data}
/** /**
* Normalize language prefs to ensure that these values only contain 2-letter * Normalize language prefs to ensure that these values only contain 2-letter
* country codes without region. * country codes without region.
*/ */
try { try {
const next = {...data.languagePrefs} const langPrefs = {...next.languagePrefs}
next.primaryLanguage = normalizeLanguageTagToTwoLetterCode( langPrefs.primaryLanguage = normalizeLanguageTagToTwoLetterCode(
next.primaryLanguage, langPrefs.primaryLanguage,
) )
next.contentLanguages = next.contentLanguages.map(lang => langPrefs.contentLanguages = langPrefs.contentLanguages.map(lang =>
normalizeLanguageTagToTwoLetterCode(lang), normalizeLanguageTagToTwoLetterCode(lang),
) )
next.postLanguage = next.postLanguage langPrefs.postLanguage = langPrefs.postLanguage
.split(',') .split(',')
.map(lang => normalizeLanguageTagToTwoLetterCode(lang)) .map(lang => normalizeLanguageTagToTwoLetterCode(lang))
.filter(Boolean) .filter(Boolean)
.join(',') .join(',')
next.postLanguageHistory = next.postLanguageHistory.map(postLanguage => { langPrefs.postLanguageHistory = langPrefs.postLanguageHistory.map(
return postLanguage postLanguage => {
.split(',') return postLanguage
.map(lang => normalizeLanguageTagToTwoLetterCode(lang)) .split(',')
.filter(Boolean) .map(lang => normalizeLanguageTagToTwoLetterCode(lang))
.join(',') .filter(Boolean)
}) .join(',')
// mutate last in case anything above fails },
data.languagePrefs = next )
next.languagePrefs = langPrefs
} catch (e: any) { } catch (e: any) {
logger.error(`persisted state: failed to normalize language prefs`, { logger.error(`persisted state: failed to normalize language prefs`, {
safeMessage: e.message, safeMessage: e.message,
}) })
} }
return data return next
} }
export function normalizeLanguageTagToTwoLetterCode(lang: string) { export function normalizeLanguageTagToTwoLetterCode(lang: string) {