Skip to content

Instantly share code, notes, and snippets.

@Bishwas-py
Created January 9, 2024 09:16
Show Gist options
  • Save Bishwas-py/704197143058600c87222fb26c3f9b9c to your computer and use it in GitHub Desktop.
Save Bishwas-py/704197143058600c87222fb26c3f9b9c to your computer and use it in GitHub Desktop.
django ninja/fastapi/pydantic loc errors to readable data
export type MessageType = 'success' | 'error' | 'warning' | 'info';
type MessageOutCommon = {
message_type?: MessageType
alias: string;
action_path?: string;
};
type MessageSingle = MessageOutCommon & {
message: string;
messages?: never;
};
type MessageMultiple = MessageOutCommon & {
message?: never;
messages: string[];
};
export type MessageOut = MessageSingle | MessageMultiple;
export type FlashMessage = {
path: string;
} & MessageOut;
export type ToastNotification = {
autoDismissDuration: number;
id: string;
message_type: MessageType;
} & MessageOut;
export type Inline = {
inline: Record<string, string | string[]>;
}
export type ValidationError = {
type: string;
loc: ['body', 'data', ...string[]];
msg: string;
ctx?: Record<string, string>;
};
/*
Code by @friendofsvelte
*/
export function translate_detail_to_message(details: ValidationError[], message_type: MessageType = 'error'): MessageOut[] {
return details.map(detail => {
const message_out: MessageOut = {
message_type: message_type,
alias: detail.type,
message: detail.msg
};
return message_out;
});
}
export function translate_detail_to_inline(details: ValidationError[]): Inline {
const inline: Inline = {
inline: {}
};
details.forEach(detail => {
inline.inline[detail.loc[detail.loc.length - 1]] = detail.msg;
});
return inline;
}
export function find_error_with_error_name(error_name: string, details: ValidationError[]) {
return details.find(detail => detail.type === error_name);
}
export function find_error_with_error_loc(error_loc: string, details: ValidationError[], loc_position: number = 2) {
return details.find(detail => detail.loc[loc_position] === error_loc);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment