Skip to content

Commit

Permalink
feat(validation): add Yup adapter
Browse files Browse the repository at this point in the history
  • Loading branch information
TheEdoRan committed Jul 19, 2024
1 parent bdf42f1 commit 3c18fd3
Show file tree
Hide file tree
Showing 3 changed files with 69 additions and 1 deletion.
4 changes: 3 additions & 1 deletion packages/next-safe-action/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -84,14 +84,16 @@
"typescript": "^5.5.3",
"typescript-eslint": "^7.8.0",
"valibot": "^0.36.0",
"yup": "^1.4.0",
"zod": "^3.23.6"
},
"peerDependencies": {
"next": ">= 14.0.0",
"react": ">= 18.2.0",
"react-dom": ">= 18.2.0",
"valibot": ">= 0.36.0",
"zod": ">= 3.0.0"
"zod": ">= 3.0.0",
"yup": ">= 1.0.0"
},
"peerDependenciesMeta": {
"zod": {
Expand Down
38 changes: 38 additions & 0 deletions packages/next-safe-action/src/adapters/yup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
// https://github.com/decs/typeschema/blob/main/packages/yup/src/validation.ts

import type { Schema as YupSchema } from "yup";
import { ValidationError } from "yup";
import type { IfInstalled, Infer, ValidationAdapter, ValidationIssue } from "../adapters.types";

class YupAdapter implements ValidationAdapter {
async validate<S extends IfInstalled<YupSchema>>(schema: S, data: unknown) {
try {
const result = await schema.validate(data, { strict: true });

return {
success: true,
data: result as Infer<S>,
} as const;
} catch (e) {
if (e instanceof ValidationError) {
const { message, path } = e;

return {
success: false,
issues: [
{
message,
path: path && path.length > 0 ? path : undefined,
},
] as ValidationIssue[],
} as const;
}

throw e;
}
}
}

export function yupAdapter() {
return new YupAdapter();
}
28 changes: 28 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 3c18fd3

Please sign in to comment.