diff --git a/bun.lockb b/bun.lockb new file mode 100755 index 0000000..fedd9bd Binary files /dev/null and b/bun.lockb differ diff --git a/package.json b/package.json index 9eca2ba..ed81f97 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@foundry/hammerstone", - "version": "0.3.0", + "version": "0.3.1", "description": "Load and manipulate Obsidian vault data", "type": "module", "exports": "./bin/hammerstone.js", diff --git a/src/document.ts b/src/document.ts index 4d599d0..890e146 100644 --- a/src/document.ts +++ b/src/document.ts @@ -177,6 +177,54 @@ export default class MarkdownDocument { return this; } + /** + * Retrieves the value of a frontmatter key as a string. + * If the key is not found, returns the provided default value. + * Throws an error if the value is not a string. + * + * @param key - The key of the frontmatter value to retrieve. + * @param defaultValue - The default value to return if the key is not found. + * @returns The value of the frontmatter key as a string. + * @throws Error if the frontmatter key is not a string. + */ + getFrontmatterString(key: string, defaultValue: string): string { + const val = this._frontmatter[key]; + + if (val === undefined) { + return defaultValue; + } + + if (typeof val !== "string") { + throw new Error(`Frontmatter key is not a string: ${key}`); + } + + return val; + } + + /** + * Retrieves an array value from the frontmatter object based on the provided key. + * If the value is not found, it returns the provided defaultValue. + * If the value is found but is not an array, it throws an error. + * + * @param key - The key to retrieve the array value from the frontmatter object. + * @param defaultValue - The default value to return if the key is not found in the frontmatter object. + * @returns The array value associated with the provided key, or the defaultValue if the key is not found. + * @throws Error if the value associated with the key is found but is not an array. + */ + getFrontmatterArray(key: string, defaultValue: string[]): string[] { + const val = this._frontmatter[key]; + + if (val === undefined) { + return defaultValue; + } + + if (!Array.isArray(val)) { + throw new Error(`Frontmatter key is not an array: ${key}`); + } + + return val; + } + /** The markdown portion of the file (without frontmatter) */ get markdown() { return this._markdown;