Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add-zod(5): Add makeProps #504

Merged
merged 16 commits into from
Sep 24, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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'
FlorianWendelborn marked this conversation as resolved.
Show resolved Hide resolved
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.
FlorianWendelborn marked this conversation as resolved.
Show resolved Hide resolved
*
* @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)
carsoli marked this conversation as resolved.
Show resolved Hide resolved

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
}