summaryrefslogtreecommitdiff
path: root/node_modules/@11ty/eleventy/src/Util/GetJavaScriptData.js
blob: 7d72a64f89dd910c9d24bf0d20a05b6c011f156e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import EleventyBaseError from "../Errors/EleventyBaseError.js";

class JavaScriptInvalidDataFormatError extends EleventyBaseError {}

export default async function (inst, inputPath, key = "data", options = {}) {
	let { mixins, isObjectRequired } = Object.assign(
		{
			mixins: {},
			isObjectRequired: true,
		},
		options,
	);

	if (inst && key in inst) {
		// get extra data from `data` method,
		// either as a function or getter or object literal
		let result = await (typeof inst[key] === "function"
			? Object.keys(mixins).length > 0
				? inst[key].call(mixins)
				: inst[key]()
			: inst[key]);

		if (isObjectRequired && typeof result !== "object") {
			throw new JavaScriptInvalidDataFormatError(
				`Invalid data format returned from ${inputPath}: typeof ${typeof result}`,
			);
		}
		return result;
	}
}