Skip to content

Commit

Permalink
refactor(#285): Add zod
Browse files Browse the repository at this point in the history
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
FlorianWendelborn authored and carsoli committed Sep 22, 2021
1 parent 9e0bad2 commit 019479f
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 1 deletion.
3 changes: 2 additions & 1 deletion packages/kotti-ui/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@
"normalize.css": "^8.0.1",
"tippy.js": "6.x",
"ts-custom-error": "^3.1.1",
"vue-clickaway": "^2.2.2"
"vue-clickaway": "^2.2.2",
"zod": "^3.8.2"
},
"description": "Kotti Vue Component UI",
"devDependencies": {
Expand Down
54 changes: 54 additions & 0 deletions packages/kotti-ui/source/props.ts
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
}

0 comments on commit 019479f

Please sign in to comment.