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'
export function normalizeData(data: Schema) {
const next = {...data}
/**
* Normalize language prefs to ensure that these values only contain 2-letter
* country codes without region.
*/
try {
const next = {...data.languagePrefs}
next.primaryLanguage = normalizeLanguageTagToTwoLetterCode(
next.primaryLanguage,
const langPrefs = {...next.languagePrefs}
langPrefs.primaryLanguage = normalizeLanguageTagToTwoLetterCode(
langPrefs.primaryLanguage,
)
next.contentLanguages = next.contentLanguages.map(lang =>
langPrefs.contentLanguages = langPrefs.contentLanguages.map(lang =>
normalizeLanguageTagToTwoLetterCode(lang),
)
next.postLanguage = next.postLanguage
langPrefs.postLanguage = langPrefs.postLanguage
.split(',')
.map(lang => normalizeLanguageTagToTwoLetterCode(lang))
.filter(Boolean)
.join(',')
next.postLanguageHistory = next.postLanguageHistory.map(postLanguage => {
return postLanguage
.split(',')
.map(lang => normalizeLanguageTagToTwoLetterCode(lang))
.filter(Boolean)
.join(',')
})
// mutate last in case anything above fails
data.languagePrefs = next
langPrefs.postLanguageHistory = langPrefs.postLanguageHistory.map(
postLanguage => {
return postLanguage
.split(',')
.map(lang => normalizeLanguageTagToTwoLetterCode(lang))
.filter(Boolean)
.join(',')
},
)
next.languagePrefs = langPrefs
} catch (e: any) {
logger.error(`persisted state: failed to normalize language prefs`, {
safeMessage: e.message,
})
}
return data
return next
}
export function normalizeLanguageTagToTwoLetterCode(lang: string) {