Skip to content

Commit

Permalink
Adds zod example for data schema #879
Browse files Browse the repository at this point in the history
  • Loading branch information
zachleat committed Apr 17, 2024
1 parent 0038419 commit 5059025
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,9 @@
"pretty": "^2.0.0",
"rimraf": "^5.0.5",
"sass": "^1.74.1",
"vue": "^3.4.21"
"vue": "^3.4.21",
"zod": "^3.22.4",
"zod-validation-error": "^3.1.0"
},
"dependencies": {
"@11ty/dependency-tree": "^3.0.0",
Expand Down
28 changes: 28 additions & 0 deletions test/EleventyTest.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import test from "ava";
import fs from "fs";
import lodash from "@11ty/lodash-custom";
import { rimrafSync } from "rimraf";
import { z } from "zod";
import { fromZodError } from 'zod-validation-error';

import eventBus from "../src/EventBus.js";
import Eleventy from "../src/Eleventy.js";
Expand Down Expand Up @@ -1173,3 +1175,29 @@ test("Eleventy data schema (fails) #879", async (t) => {

t.is(e.originalError.toString(), "Error: Invalid data type for draft.");
});

test("Eleventy data schema (fails, using zod) #879", async (t) => {
let elev = new Eleventy("./test/stubs-virtual/", undefined, {
config: eleventyConfig => {
eleventyConfig.addTemplate("index1.html", "", {
draft: 1,
eleventyDataSchema: function(data) {
let result = z.object({
draft: z.boolean().or(z.undefined()),
}).safeParse(data);

if(result.error) {
throw fromZodError(result.error);
}
}
});
}
});
elev.disableLogger();

let e = await t.throwsAsync(() => elev.toJSON(), {
message: 'Error in the data schema for: ./test/stubs-virtual/index1.html (via `eleventyDataSchema`)'
});

t.is(e.originalError.toString(), 'Validation error: Expected boolean, received number at "draft", or Expected undefined, received number at "draft"');
});

0 comments on commit 5059025

Please sign in to comment.