Created
July 9, 2023 17:09
-
-
Save arleighdickerson/a0f8c84adc69ca273f7ddee41ebcb147 to your computer and use it in GitHub Desktop.
validateUtil
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { validate } from 'validate.js'; | |
import _ from 'lodash'; | |
interface AnyObject { | |
[key: string]: any; | |
} | |
type ValidationErrors = AnyObject | undefined; | |
export interface ApiError { | |
status: string; | |
timestamp: string | Date; | |
message: string; | |
debugMessage: string | null; | |
subErrors: ApiSubError[] | null; | |
} | |
export interface ApiSubError { | |
message: string; | |
object: string; | |
field: string; | |
rejectedValue: any; | |
} | |
export type ValidationSchema<FormValues> = { [key in keyof FormValues]: any }; | |
export namespace validateUtil { | |
export function createValidator<FormValues>(schema: ValidationSchema<FormValues>) { | |
return function (values: FormValues): ValidationErrors { | |
return _.mapValues(validate(values, schema), _.first); | |
}; | |
} | |
export function convertApiError(apiError: ApiError): ValidationErrors { | |
return _.fromPairs( | |
_.uniqBy(apiError.subErrors, v => v.field).map((apiSubError: ApiSubError) => [ | |
apiSubError.field, | |
apiSubError.message, | |
]), | |
); | |
} | |
export function isApiSubError(v: any) { | |
return ( | |
(_.isObject(v) || _.isFunction(v)) && | |
_.isString(_.get(v, 'message')) && | |
_.isString(_.get(v, 'field')) && | |
_.isString(_.get(v, 'object')) | |
); | |
} | |
export function isApiError(v: any): v is ApiError { | |
return ( | |
(_.isObject(v) || _.isFunction(v)) && | |
_.isString(_.get(v, 'status')) && | |
_.isString(_.get(v, 'message')) && | |
(_.isString(_.get(v, 'timestamp')) || _.isDate(_.get(v, 'timestamp'))) && | |
_.isArray(_.get(v, 'subErrors')) && | |
(_.get(v, 'subErrors') as unknown as any[]).every(isApiSubError) | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment