Skip to content

Commit

Permalink
Ensure data schema callbacks have access to collections #879
Browse files Browse the repository at this point in the history
  • Loading branch information
zachleat committed Apr 18, 2024
1 parent 5059025 commit 1071566
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 12 deletions.
35 changes: 23 additions & 12 deletions src/TemplateMap.js
Original file line number Diff line number Diff line change
Expand Up @@ -409,18 +409,6 @@ class TemplateMap {
} else {
let counter = 0;
for (let page of map._pages) {
// Data Schema callback #879
if (typeof page.data[this.config.keys.dataSchema] === "function") {
try {
await page.data[this.config.keys.dataSchema](page.data);
} catch (e) {
throw new EleventyDataSchemaError(
`Error in the data schema for: ${map.inputPath} (via \`eleventyDataSchema\`)`,
e,
);
}
}

// Copy outputPath to map entry
if (!map.outputPath) {
map.outputPath = page.outputPath;
Expand Down Expand Up @@ -478,6 +466,7 @@ class TemplateMap {
};
});

await this.runDataSchemas(orderedMap);
await this.populateContentDataInMap(orderedMap);

this.populateCollectionsWithContent();
Expand Down Expand Up @@ -534,6 +523,28 @@ class TemplateMap {
return orderedMap;
}

async runDataSchemas(orderedMap) {
for (let map of orderedMap) {
if (!map._pages) {
continue;
}

for (let pageEntry of map._pages) {
// Data Schema callback #879
if (typeof pageEntry.data[this.config.keys.dataSchema] === "function") {
try {
await pageEntry.data[this.config.keys.dataSchema](pageEntry.data);
} catch (e) {
throw new EleventyDataSchemaError(
`Error in the data schema for: ${map.inputPath} (via \`eleventyDataSchema\`)`,
e,
);
}
}
}
}
}

async populateContentDataInMap(orderedMap) {
let usedTemplateContentTooEarlyMap = [];
for (let map of orderedMap) {
Expand Down
21 changes: 21 additions & 0 deletions test/EleventyTest.js
Original file line number Diff line number Diff line change
Expand Up @@ -1201,3 +1201,24 @@ test("Eleventy data schema (fails, using zod) #879", async (t) => {

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

test("Eleventy data schema has access to custom collections created via API #879", async (t) => {
t.plan(2);
let elev = new Eleventy("./test/stubs-virtual/", undefined, {
config: eleventyConfig => {
eleventyConfig.addCollection("userCollection", function (collection) {
return collection.getAll();
});

eleventyConfig.addTemplate("index1.html", "", {
eleventyDataSchema: function(data) {
t.is(data.collections.userCollection.length, 1);
}
});
}
});
elev.disableLogger();

let results = await elev.toJSON();
t.is(results.length, 1);
});

0 comments on commit 1071566

Please sign in to comment.