-
Notifications
You must be signed in to change notification settings - Fork 8
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Also, this adds a surplus check so that jest sees that result.error is defined This isn’t necessary for TS itself, but somehow ts-jest didn’t see this... upgrading to latest didn’t fix this bug unfortunately, so this is as good as it gets
- Loading branch information
1 parent
9e0bad2
commit 019479f
Showing
2 changed files
with
56 additions
and
1 deletion.
There are no files selected for viewing
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,54 @@ | ||
import { cloneDeep } from 'lodash' | ||
import { z } from 'zod' | ||
|
||
/** | ||
* Easily validate vue props, improve error messages drastically | ||
* | ||
* This augments/replaces Vue’s prop.validator approach by using zod and therefore actually | ||
* prints errors to the console that can actually help developers rather than just say | ||
* "hey you failed the validator, good luck!" as vue would do by default. | ||
* | ||
* @example | ||
* sections: { | ||
* required: true, | ||
* type: Array, | ||
* validator: propValidator(KottiUserMenu.propsInternalSchema, 'sections'), | ||
* } | ||
*/ | ||
export const propValidator = < | ||
SCHEMA extends z.ZodObject<z.ZodRawShape>, | ||
KEY extends keyof z.infer<SCHEMA>, | ||
>( | ||
schema: SCHEMA, | ||
key: KEY, | ||
) => { | ||
const validator = (value: unknown) => { | ||
const result = schema.pick({ [key]: true }).safeParse({ [key]: value }) | ||
|
||
if (result.success) return true | ||
|
||
/* eslint-disable no-console */ | ||
console.group(`propValidator found issues with prop “${key}”`) | ||
|
||
// HACK: 'error' in result is necessary as `ts-jest` doesn’t see that result.success was already properly checked to be falsy and that error now exists | ||
if ('error' in result) console.error(result.error) | ||
|
||
if (Array.isArray(value)) console.table(cloneDeep(value)) | ||
else console.log(cloneDeep(value)) | ||
|
||
console.trace() | ||
|
||
console.groupEnd() | ||
/* eslint-enable no-console */ | ||
|
||
return false | ||
} | ||
|
||
// assign name for better debugging and to improve props rendering in the documentation | ||
Object.defineProperty(validator, 'name', { | ||
value: `propValidator('${key}')`, | ||
writable: false, | ||
}) | ||
|
||
return validator | ||
} |