Try not to mutate
This commit is contained in:
+18
-15
@@ -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) {
|
||||
|
||||
Reference in New Issue
Block a user