mirror of
https://github.com/Athou/commafeed.git
synced 2026-09-23 04:25:07 +00:00
Use typed backend errors for translations
This commit is contained in:
@@ -1,3 +1,5 @@
|
||||
import { i18n, type MessageDescriptor } from "@lingui/core"
|
||||
import { msg } from "@lingui/core/macro"
|
||||
import axios, { type AxiosError } from "axios"
|
||||
import type {
|
||||
AddCategoryRequest,
|
||||
@@ -6,6 +8,8 @@ import type {
|
||||
Category,
|
||||
CategoryModificationRequest,
|
||||
CollapseRequest,
|
||||
CommaFeedApplicationError,
|
||||
CommaFeedExceptionType,
|
||||
Entries,
|
||||
FeedInfo,
|
||||
FeedInfoRequest,
|
||||
@@ -31,6 +35,10 @@ import type {
|
||||
UserModel,
|
||||
} from "./types"
|
||||
|
||||
const applicationErrorMessages = {
|
||||
WRONG_USERNAME_OR_PASSWORD: msg`Wrong username or password`,
|
||||
} satisfies Record<CommaFeedExceptionType, MessageDescriptor>
|
||||
|
||||
const axiosInstance = axios.create({ baseURL: "./rest", withCredentials: true })
|
||||
axiosInstance.interceptors.response.use(
|
||||
response => response,
|
||||
@@ -128,21 +136,23 @@ export const errorToStrings = (err: unknown) => {
|
||||
let strings: string[] = []
|
||||
|
||||
if (axios.isAxiosError(err) && err.response) {
|
||||
if (typeof err.response.data === "string") strings.push(err.response.data)
|
||||
if (isMessageError(err)) strings.push(err.response.data.message)
|
||||
if (isMessageArrayError(err)) strings = [...strings, ...err.response.data.errors]
|
||||
if (isCommaFeedApplicationError(err)) {
|
||||
strings.push(i18n._(applicationErrorMessages[err.response.data.type]))
|
||||
} else {
|
||||
if (typeof err.response.data === "string") strings.push(err.response.data)
|
||||
if (isMessageError(err)) strings.push(err.response.data.message)
|
||||
if (isMessageArrayError(err)) strings = [...strings, ...err.response.data.errors]
|
||||
}
|
||||
}
|
||||
|
||||
return strings
|
||||
}
|
||||
|
||||
/**
|
||||
* Transform a login error into messages that can be displayed to the user.
|
||||
* Authentication failures use a client-provided message so it can be translated.
|
||||
*/
|
||||
export const loginErrorToStrings = (err: unknown, authenticationErrorMessage: string) => {
|
||||
if (isAuthenticationError(err)) return [authenticationErrorMessage]
|
||||
return errorToStrings(err)
|
||||
function isCommaFeedApplicationError(err: AxiosError): err is AxiosError<CommaFeedApplicationError> {
|
||||
const data = err.response?.data
|
||||
if (!data || typeof data !== "object" || !("type" in data)) return false
|
||||
const type = data.type
|
||||
return typeof type === "string" && Object.hasOwn(applicationErrorMessages, type)
|
||||
}
|
||||
|
||||
function isMessageError(err: AxiosError): err is AxiosError<{ message: string }> {
|
||||
|
||||
Reference in New Issue
Block a user