Add frontmatter helpers

This commit is contained in:
Endeavorance 2024-07-04 17:39:01 -04:00
parent 29ea947b41
commit fcbaa1bd52
3 changed files with 49 additions and 1 deletions

BIN
bun.lockb Executable file

Binary file not shown.

View file

@ -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",

View file

@ -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;