40 lines
1.1 KiB
TypeScript
40 lines
1.1 KiB
TypeScript
import type { Dictionary } from "@/i18n/dictionaries"
|
|
|
|
type RecipientActionCopy = Dictionary["inventory"]["recipients"]["actions"]
|
|
|
|
type FieldErrors = Record<string, string[]>
|
|
|
|
const recipientErrorMessageKeys = {
|
|
"Username already exists": "duplicateUsername",
|
|
"Email already exists": "duplicateEmail",
|
|
} as const satisfies Record<string, keyof RecipientActionCopy>
|
|
|
|
function isRecipientErrorMessage(
|
|
message: string,
|
|
): message is keyof typeof recipientErrorMessageKeys {
|
|
return message in recipientErrorMessageKeys
|
|
}
|
|
|
|
function localizeRecipientMessage(
|
|
message: string,
|
|
copy: RecipientActionCopy,
|
|
): string {
|
|
if (!isRecipientErrorMessage(message)) return message
|
|
|
|
return copy[recipientErrorMessageKeys[message]]
|
|
}
|
|
|
|
export function localizeRecipientFieldErrors(
|
|
errors: FieldErrors | undefined,
|
|
copy: RecipientActionCopy,
|
|
): FieldErrors | undefined {
|
|
if (!errors) return undefined
|
|
|
|
return Object.fromEntries(
|
|
Object.entries(errors).map(([field, messages]) => [
|
|
field,
|
|
messages.map((message) => localizeRecipientMessage(message, copy)),
|
|
]),
|
|
)
|
|
}
|