Preparing search index...

    Class RecipeDatabase

    RecipeDatabase - Singleton class for managing recipe data storage and operations

    This class provides a comprehensive interface for managing recipes, ingredients, tags, and shopping lists using SQLite database. It implements the singleton pattern to ensure a single database instance throughout the application lifecycle.

    Key Features:

    • Recipe CRUD operations with ingredient and tag relationships
    • Fuzzy search for recipe titles via FuzzyIndex utility
    • Shopping list generation from recipes
    • Quantity scaling for different serving sizes
    • Similar recipe detection
    • Local caching for improved performance
    const db = RecipeDatabase.getInstance();
    await db.init();

    const recipe = await db.addRecipe({
    title: "Chocolate Cake",
    ingredients: [...],
    tags: [...]
    });
    Index
    getInstance resetInstance scaleRecipeToPersons subscribe closeAndReset init performInit isDatabaseEmpty addIngredient addTag addMultipleIngredients addMultipleTags addRecipe addMultipleRecipes editRecipe editIngredient applyIngredientToRecipe applyTagToRecipe editTag searchRandomlyTags getRandomIngredientsByType getRandomTags deleteRecipe deleteIngredient deleteTag get_recipes isRecipeExist get_ingredients get_tags add_recipes add_ingredient add_tags remove_recipe remove_ingredient remove_tag update_recipe update_multiple_recipes update_ingredient update_tag find_recipe find_ingredient find_tag get_menu isRecipeInMenu addRecipeToMenu toggleMenuItemCooked removeFromMenu clearMenu get_purchasedIngredients setPurchased clearPurchasedIngredients prunePurchasedIngredients commitMenuChange scaleAndUpdateRecipe findSimilarRecipes getImportedSourceUrls getSeenUrls markUrlsAsSeen removeFromSeenHistory getDismissedUrls getDismissedRecipes markRecipesAsDismissed restoreDismissedRecipes prepareRecipe insertAndCacheRecipes getAllPurchasedIngredients encodePurchasedIngredient notify reset constructUpdateRecipeStructure constructUpdateIngredientStructure constructUpdateTagStructure openDatabase deleteDatabase verifyTagsExist verifyIngredientsExist encodeRecipe prepareRecipeImage decodeRecipe decodeArrayOfRecipe buildDecodeIndexes reportUnresolvedReferences recordDecodeError get_decode_error encodeIngredient decodeIngredientFromRecipe computeRecipeSeason encodeIngredientForDb encodeTagForDb decodeIngredient decodeArrayOfIngredients reportDuplicateIds decodeSeason encodeTagForRecipe decodeTagFromRecipe decodeTag decodeArrayOfTags encodeNutrition decodeNutrition decodePreparation getAllRecipes getAllTags getAllIngredients getAllMenu encodeMenu decodeMenu decodeArrayOfMenu reportUnresolvedMenuRecipes areIngredientsSimilar migrateAddSourceColumns getAllImportHistory decodeImportHistory encodeImportHistory getAllDismissedRecipes decodeDismissedRecipe encodeDismissedRecipe
    _databaseName: string
    _dbConnection: SQLiteDatabase
    _recipesTable: TableManipulation
    _ingredientsTable: TableManipulation
    _tagsTable: TableManipulation
    _importHistoryTable: TableManipulation
    _dismissedRecipesTable: TableManipulation
    _menuTable: TableManipulation
    _purchasedIngredientsTable: TableManipulation
    _recipes: recipeTableElement[]
    _ingredients: ingredientTableElement[]
    _importHistory: importHistoryTableElement[]
    _dismissedRecipes: dismissedRecipeTableElement[]
    _purchasedIngredients: Map<string, boolean>
    _listeners: Map<StoreSlice, Set<() => void>> = ...
    _isReady: boolean = false
    _initPromise: Promise<void> | null = null
    _decodeError: Error | null = null
    • Tears down the singleton instance completely.

      Closes the database connection, clears every registered store listener, and discards the cached singleton so the next getInstance call builds a fresh instance. Call this when the app reinitializes its data layer (e.g. a settings reset or full data wipe) to guarantee no stale instance keeps its listeners registered and firing store notifications alongside the new one.

      Returns Promise<void>

      Promise that resolves once teardown is complete. No-op if no instance currently exists.

    • Scales a recipe's ingredient quantities to a different number of persons

      Creates a new recipe object with ingredient quantities adjusted proportionally for the target number of persons. If the recipe doesn't have a valid person count or already matches the target, returns the recipe unchanged.

      Type Parameters

      Parameters

      • recipe: T

        The recipe to scale

      • targetPersons: number

        The target number of persons to scale for

      Returns T

      New recipe object with scaled ingredient quantities

      const originalRecipe = {
      title: "Pasta",
      persons: 4,
      ingredients: [{ name: "Pasta", quantity: "400", unit: "g" }]
      };

      const scaledRecipe = RecipeDatabase.scaleRecipeToPersons(originalRecipe, 2);
      // scaledRecipe.persons === 2
      // scaledRecipe.ingredients[0].quantity === "200"
    • Subscribes a callback to notifications for a specific data slice.

      Called by useSyncExternalStore to register a re-render callback. Returns an unsubscribe function that removes the callback from the listener set.

      Parameters

      • slice: StoreSlice

        The data slice to subscribe to

      • callback: () => void

        Function to call when the slice changes

      Returns () => void

      Unsubscribe function

    • Closes the database connection and resets all internal state

      Use this method in test teardown (afterEach) to properly cleanup database resources between tests.

      Returns Promise<void>

      Promise that resolves when cleanup is complete

    • Initializes the database by creating tables and loading data into local cache

      This method must be called before using any other database operations. It creates the necessary tables if they don't exist and loads all data into memory for faster access.

      Returns Promise<void>

      Promise that resolves when initialization is complete

      const db = RecipeDatabase.getInstance();
      await db.init();
      console.log('Database ready for use');
    • Checks if the database is empty

      Determines whether the database contains any data by checking if all three main tables (recipes, ingredients, and tags) are empty. This is useful for preventing duplicate data insertion during app initialization.

      Returns boolean

      True if all main tables are empty, false if any table contains data

      const db = RecipeDatabase.getInstance();
      await db.init();

      if (db.isDatabaseEmpty()) {
      console.log('Database is empty, loading initial data...');
      await db.addMultipleRecipes(initialRecipes);
      }
    • Adds a new ingredient to the database

      Parameters

      Returns Promise<ingredientTableElement>

      Promise resolving to the added ingredient with database ID

      Error if ingredient insertion or retrieval fails

      const ingredient = await db.addIngredient({
      name: "Flour",
      unit: "cups",
      type: ingredientType.grain,
      season: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"]
      });
      console.log(`Ingredient added with ID: ${ingredient.id}`);
    • Adds a new tag to the database

      Parameters

      • newTag: TagDraft

        The tag object to add

      Returns Promise<tagTableElement>

      Promise resolving to the added tag with database ID

      Error if tag insertion or retrieval fails

      const tag = await db.addTag({ name: "Dessert" });
      console.log(`Tag added with ID: ${tag.id}`);
    • Adds multiple ingredients to the database in a single batch operation

      Performs a batch insert for improved performance when adding multiple ingredients. Uses a database transaction to ensure atomicity and efficiency.

      Parameters

      Returns Promise<void>

      await db.addMultipleIngredients([
      {
      name: "Flour",
      unit: "cups",
      type: ingredientType.grain,
      season: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"]
      },
      {
      name: "Sugar",
      unit: "cups",
      type: ingredientType.sweetener,
      season: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"]
      }
      ]);
    • Adds multiple tags to the database in a single batch operation

      Performs a batch insert for improved performance when adding multiple tags. Uses a database transaction to ensure atomicity and efficiency.

      Parameters

      • tags: TagDraft[]

        Array of tag objects to add

      Returns Promise<void>

      await db.addMultipleTags([
      { name: "Dessert" },
      { name: "Quick & Easy" },
      { name: "Vegetarian" }
      ]);
    • Adds a new recipe to the database

      This method verifies that all ingredients and tags exist in the database, adding them automatically if they don't exist.

      Parameters

      Returns Promise<recipeTableElement>

      The persisted recipe, decoded from the database with its assigned id

      Error if the database insertion or the post-insert lookup fails

      await db.addRecipe({
      title: "Chocolate Cake",
      description: "Delicious chocolate cake",
      ingredients: [
      { name: "Flour", quantity: "2 cups", unit: "cups", type: "grain" }
      ],
      tags: [{ name: "Dessert" }],
      persons: 8,
      time: 45,
      preparation: ["Mix ingredients", "Bake for 30 minutes"]
      });
    • Adds multiple recipes to the database, skipping any that fail validation.

      Prepares all recipes in parallel via Promise.allSettled, logs a warning for each rejected one, then batch-inserts the valid ones.

      Parameters

      Returns Promise<void>

    • Updates an existing recipe in the database.

      Verifies all tags and ingredients exist in the database and saves any temporary image to permanent storage before persisting the update, then refreshes the in-memory cache and notifies recipes subscribers.

      Parameters

      • recipe: Omit<Draft<recipeTableElement>, "tags" | "ingredients"> & {
            id?: number;
            ingredients: IngredientDraft[];
            tags: TagDraft[];
        } & { id: number }

        The existing recipe to update, carrying its persisted id.

      Returns Promise<recipeTableElement>

      The prepared recipe object with verified tags and ingredients.

      Error if any tags or ingredients are not found in the database.

    • Updates an existing ingredient in the database.

      After a successful update the in-memory ingredients cache is refreshed and every cached recipe that references this ingredient is patched in place, then both the ingredients and recipes store slices are notified.

      Parameters

      Returns Promise<boolean>

      true if the update succeeded, false otherwise.

    • Private

      Re-resolves an updated ingredient inside a cached recipe

      Recipes embed a copy of each ingredient they use, so an ingredient rename or unit change has to be reflected in every recipe referencing it. The recipe-specific quantity and note are preserved and the recipe season is recomputed. Recipes that do not use the ingredient are returned untouched.

      Parameters

      Returns recipeTableElement

      The patched recipe, or the original one when unaffected

    • Updates an existing tag in the database.

      After a successful update the in-memory tags cache is refreshed and every cached recipe that references this tag is patched in place, then both the tags and recipes store slices are notified.

      Parameters

      Returns Promise<boolean>

      true if the update succeeded, false otherwise.

    • Returns a random sample of tags from the local cache.

      If the cache contains fewer tags than requested, all available tags are returned. When the cache is empty an empty array is returned immediately.

      Parameters

      • numOfElements: number

        Number of distinct random tags to return.

      Returns tagTableElement[]

      Array of randomly selected tags, length ≤ numOfElements.

    • Deletes a recipe from the database and performs related cleanup.

      In addition to removing the recipe row, this method:

      • Deletes the associated image file if it is stored in permanent storage.
      • Removes any corresponding menu entry.
      • Removes the recipe URL from the seen-history if it originated from a provider.

      Parameters

      Returns Promise<boolean>

      true if the recipe was deleted, false otherwise.

    • Deletes an ingredient from the database and removes it from all recipes.

      Any recipe that referenced the deleted ingredient is updated in-place to drop that ingredient, and both the ingredients and recipes store slices are notified after the operation completes.

      Parameters

      • ingredient: ingredientTableElement

        The ingredient to delete. Matched by id if present, otherwise by name/unit/type.

      Returns Promise<boolean>

      true if the ingredient was deleted, false otherwise.

    • Deletes a tag from the database and removes it from all recipes.

      Any recipe that referenced the deleted tag is updated in-place to drop that tag, and both the tags and recipes store slices are notified after the operation completes.

      Parameters

      • tag: tagTableElement

        The tag to delete. Matched by id if present, otherwise by name.

      Returns Promise<boolean>

      true if the tag was deleted, false otherwise.

    • Removes a tag from the in-memory cache without touching the database.

      Matches by id when present, otherwise uses full equality. Logs a warning if the tag is not found. Prefer deleteTag for full persistence.

      Parameters

      Returns void

    • Replaces multiple recipes in the in-memory cache in a single pass.

      Uses a pre-built id→index Map for O(n) performance. Logs a warning for any recipe in updatedRecipes whose id is not found in the current cache.

      Parameters

      • updatedRecipes: recipeTableElement[]

        Array of updated recipes. Each must have a valid id.

      Returns void

    • Checks if a recipe is already in the menu

      Parameters

      • recipeId: number

        The recipe ID to check

      Returns boolean

      True if recipe is in menu, false otherwise

    • Adds a recipe to the menu and regenerates the shopping list

      If the recipe is already in the menu, increments its count. Otherwise, it adds the recipe to the menu table with count = 1.

      Parameters

      Returns Promise<void>

    • Toggles the cooked status of a menu item

      Parameters

      • menuId: number

        The menu item ID to toggle

      Returns Promise<boolean>

      True if successful, false otherwise

    • Decrements the count of a menu item, removing it if count reaches 0

      Parameters

      • menuId: number

        The menu item ID to decrement/remove

      Returns Promise<boolean>

      True if successful, false otherwise

    • Returns the map of purchased ingredient states Key is ingredient name, value is whether it's purchased

      Returns Map<string, boolean>

    • Sets the purchase state for an ingredient

      Parameters

      • ingredientName: string

        The ingredient name

      • purchased: boolean

        Whether the ingredient is purchased

      Returns Promise<void>

    • Clears all purchased ingredient states Called when the menu is cleared to start fresh

      Returns Promise<void>

    • Drops purchase state for ingredients that left the shopping list

      Purchase state is keyed by ingredient name and outlives the menu item that put the ingredient on the list, so it must be pruned whenever the menu changes: cooking or removing a recipe would otherwise leave a flag behind that reappears — still checked — the next time the ingredient is shopped for. Ingredients still required by another non-cooked menu item keep their state.

      Only menu changes prune. The shopping list also derives from the recipe catalogue, so editing a recipe's ingredients or deleting an ingredient can leave a flag behind until the next menu mutation clears it.

      Returns Promise<void>

    • Applies the shared post-condition of every menu mutation

      Purchase state is keyed by ingredient name and outlives the menu item that put the ingredient on the list, so it must be pruned wherever the menu changes — routing every mutation through here keeps that invariant in one place instead of at the call sites that happened to need it.

      Returns Promise<void>

    • Scales and updates a single recipe in the database

      Takes a pre-scaled recipe object and updates it in the database. This method is used for individual recipe updates during progressive scaling operations.

      Parameters

      • scaledRecipe: Omit<Draft<recipeTableElement>, "tags" | "ingredients"> & {
            id?: number;
            ingredients: IngredientDraft[];
            tags: TagDraft[];
        } & { id: number }

        The recipe to persist, already scaled to target persons. Carries its database id; its embedded tags/ingredients are normally already resolved, but any unresolved one causes encodeRecipe to throw before the row is touched.

      Returns Promise<void>

      Error if a tag/ingredient cannot be resolved, or if the update fails

      const recipe = db.get_recipes()[0];
      const scaledRecipe = RecipeDatabase.scaleRecipeToPersons(recipe, 4);
      await db.scaleAndUpdateRecipe(scaledRecipe);
    • Finds recipes with similar ingredients and quantities

      Uses ingredient comparison and fuzzy text matching to find recipes that share similar ingredients and cooking methods.

      Parameters

      • recipeToCompare: RecipeDraft

        The recipe to find similarities for

      Returns recipeTableElement[]

      Array of similar recipes

      const similar = db.findSimilarRecipes(myRecipe);
      console.log(`Found ${similar.length} similar recipes`);
    • Gets all imported recipe source URLs for a specific provider

      Returns URLs of recipes that have been successfully imported from the given provider. These recipes should be hidden from future discovery.

      Parameters

      • providerId: string

        The provider identifier (e.g., 'hellofresh')

      Returns Set<string>

      Set of source URLs for imported recipes

    • Gets all seen-but-not-imported recipe URLs for a specific provider

      Returns URLs of recipes that were discovered but not imported. These recipes should be shown with a visual indicator.

      Parameters

      • providerId: string

        The provider identifier (e.g., 'hellofresh')

      Returns Set<string>

      Set of URLs for seen-but-not-imported recipes

    • Marks recipe URLs as seen for a specific provider

      Records that the user has seen these recipes during discovery. Only adds new entries for URLs not already tracked.

      Parameters

      • providerId: string

        The provider identifier (e.g., 'hellofresh')

      • urls: string[]

        Array of recipe URLs to mark as seen

      Returns Promise<void>

    • Removes recipe URLs from seen history for a specific provider

      Called after successful import to remove URLs from the "seen" list since they are now tracked as imported recipes.

      Parameters

      • providerId: string

        The provider identifier (e.g., 'hellofresh')

      • urls: string[]

        Array of recipe URLs to remove from seen history

      Returns Promise<void>

    • Gets all permanently dismissed recipe URLs for a specific provider.

      Dismissed recipes were explicitly hidden by the user and must be filtered out of every future bulk-import discovery run.

      Parameters

      • providerId: string

        The provider identifier (e.g., 'hellofresh')

      Returns Set<string>

      Set of URLs the user has dismissed

    • Gets dismissed recipe records, optionally scoped to a provider.

      Returns the full records (including title) so the manage list can display them without re-running discovery. Sorted most-recently-dismissed first. When providerId is omitted, records from every provider are returned.

      Parameters

      • OptionalproviderId: string

        Optional provider identifier to filter by (e.g., 'hellofresh')

      Returns dismissedRecipeTableElement[]

      Array of dismissed recipe records, newest first

    • Permanently dismisses recipes for a specific provider.

      Records that the user never wants to see these recipes again. Already-dismissed URLs are skipped. Dismissed recipes are excluded from all future discovery runs.

      Parameters

      • providerId: string

        The provider identifier (e.g., 'hellofresh')

      • recipes: { url: string; title: string; imageUrl?: string }[]

        Recipes to dismiss, each providing its url, title and optional imageUrl

      Returns Promise<void>

    • Restores previously dismissed recipes for a specific provider.

      Removes the dismissal so the recipes reappear in future discovery runs. Used by the undo action and the manage list. Deletion is keyed on provider + URL, so it works regardless of whether the in-memory record carries a database id yet.

      Parameters

      • providerId: string

        The provider identifier (e.g., 'hellofresh')

      • urls: string[]

        Array of recipe URLs to restore

      Returns Promise<void>

    • Validates and prepares a single recipe for insertion.

      Verifies that all referenced tags and ingredients exist in the database, then resolves the image source. Throws if any references are missing.

      Type Parameters

      Parameters

      • rec: T

        The recipe to prepare

      Returns Promise<PreparedRecipe<T>>

      Prepared recipe ready for encoding and insertion

      Error if any tags or ingredients are not found in the database

    • Batch-inserts prepared recipes into the database and updates the in-memory cache.

      Parameters

      • recipes: RecipeDraft[]

        Already-validated and prepared recipes to insert

      Returns Promise<void>

      Error if the batch database insertion fails

    • Loads all purchased ingredients from the database

      Returns Promise<Map<string, boolean>>

      Map of ingredient name to purchased state

    • Encodes a purchased ingredient element for database storage

      Parameters

      • element: { ingredientName: string; purchased: boolean }

      Returns Record<string, string | number>

    • Fires all registered callbacks for the given store slice.

      Called after every mutation so that useSyncExternalStore subscribers know to re-read the store snapshot.

      Parameters

      • slice: StoreSlice

        The data slice whose listeners should be triggered.

      Returns void

    • Resets all in-memory caches to their initial empty values.

      Does not touch the database — use closeAndReset for a full teardown that also closes the SQLite connection.

      Returns void

    • Private

      Constructs a Map structure for updating recipe data in the database

      Converts an encoded recipe element into a Map structure suitable for database update operations, mapping column names to their corresponding values.

      Parameters

      Returns Map<string, string | number>

      Map with column names as keys and recipe data as values

    • Private

      Constructs a Map structure for updating ingredient data in the database

      Converts an ingredient element into a Map structure suitable for database update operations, properly encoding seasonal data with separators.

      Parameters

      Returns Map<string, string | number>

      Map with column names as keys and ingredient data as values

    • Private

      Constructs a Map structure for updating tag data in the database

      Converts a tag element into a Map structure suitable for database update operations.

      Parameters

      Returns Map<string, string | number>

      Map with column names as keys and tag data as values

    • Private

      Opens a connection to the SQLite database

      Creates and establishes a connection to the SQLite database using the configured database name. Logs success/failure for debugging purposes.

      Returns Promise<void>

      Will log error if database connection fails

    • Private

      Completely removes the database file and resets the instance

      Closes the current database connection, deletes the database file from storage, and resets all internal data structures to their initial state.

      Returns Promise<void>

      Will log error if database deletion fails

    • Private

      Verifies that all tags exist in the database and returns them with database IDs

      Checks each tag against the local cache and returns the database versions. Throws an error listing all tags that are not found in the database.

      Parameters

      • tags: TagDraft[]

        Array of tags to verify

      Returns tagTableElement[]

      Array of tags with database IDs

      Error if any tags are not found in the database, listing all missing tags

    • Private

      Verifies that all ingredients exist in the database and returns them with database IDs

      Checks each ingredient against the local cache and returns the database versions with recipe-specific quantities and optional usage notes. Throws an error listing all ingredients that are not found.

      Parameters

      Returns ingredientTableElement[]

      Array of ingredients with database IDs, recipe-specific quantities, and notes

      Error if any ingredients are not found in the database, listing all missing ingredients

    • Private

      Encodes a recipe object for database storage

      Converts a recipe from the application format to the database storage format, encoding all nested objects (tags, ingredients, preparation steps, nutrition) into string representations using appropriate separators.

      Parameters

      • recToEncode: RecipeDraft

        The recipe object to encode for database storage

      Returns encodedRecipeElement

      Encoded recipe element ready for database insertion/update

    • Private

      Prepares recipe image URI for database storage

      Handles temporary image URIs by saving them to permanent storage. If the image URI is already in permanent storage, returns it unchanged. This encapsulates all image preparation logic within the database layer.

      Parameters

      • imageUri: string

        The image URI from the recipe (temporary or permanent)

      • recipeTitle: string

        The recipe title used for filename generation

      Returns Promise<string>

      Promise resolving to the permanent image URI

    • Private

      Decodes a recipe from database storage format to application format

      Converts an encoded recipe element from the database into the full application format, decoding all nested data structures (ingredients, tags, preparation, nutrition) and resolving file paths and database references.

      Parameters

      Returns recipeTableElement

      Promise resolving to fully decoded recipe object

    • Private

      Decodes an array of recipes from database storage format

      Processes multiple encoded recipe elements from database queries, decoding each one into the full application format. The ingredient and tag lookup indexes are built once and shared across the whole batch.

      Parameters

      Returns recipeTableElement[]

      Array of fully decoded recipe objects

    • Private

      Builds id-keyed lookup indexes over the cached ingredients and tags

      Recipe rows only store ingredient and tag ids, so decoding needs to resolve each id to its full element. Both tables are already fully cached in memory, so the lookups are served from these maps instead of one query per reference.

      Returns decodeIndexes

      Ingredient and tag lookup maps keyed by database id, plus the sets collecting the ids that decoding could not resolve

    • Private

      Reports references that a decode pass could not resolve against the caches

      Every ingredient and tag a recipe row points at must exist in the caches, which mirror their whole tables. An unresolved id therefore means either a cache that drifted from the database or a recipe row pointing at a deleted row — both silently drop data from the decoded recipe, so they are logged as errors. Ids are reported once per decode pass rather than once per reference.

      Parameters

      • indexes: decodeIndexes

        Decode indexes carrying the unresolved id sets

      • decodedRecipeCount: number

        Number of recipes the decode pass covered

      Returns void

    • Private

      Logs a corrupt-data condition found while decoding a table, and records it

      Decoding resolves cross-table references and casts stored strings into application types; neither can be trusted blindly, and a failure means the decoded row silently loses data. Every failure is logged. In development and E2E builds the first one is also kept, so the UI layer can rethrow it during render and let the root error boundary replace the app with the recovery screen — making the corruption impossible to miss. Production keeps the log and degrades the affected row rather than taking the whole app down.

      Logging and recording live together so a future check cannot do one without the other, and publishes on the recipes slice so a subscriber mounted before the failure re-renders and can surface it.

      Parameters

      • message: string

        What was found to be corrupt, including the offending ids

      • context: Record<string, unknown>

        Structured detail for the log entry

      Returns void

    • Returns the first corrupt-data condition found while decoding, if any.

      Always null in production builds.

      Returns Error | null

      The recorded decode error, or null when every decode succeeded

    • Private

      Encodes an ingredient for storage within a recipe's ingredients list

      Converts an ingredient to a string representation containing the ingredient's database ID, quantity, and optional usage note. Used when storing ingredient references within recipe data.

      Format: "ID--quantity" or "ID--quantity%%note" if note is present. This allows the same ingredient to appear multiple times with different usage contexts (e.g., "olive oil" for sauce vs garnish).

      Parameters

      Returns string

      Encoded string representation of the ingredient

      Error if the ingredient cannot be resolved in the database

      // Without note
      encodeIngredient({id: 1, quantity: "200", ...}) // "1--200"

      // With note
      encodeIngredient({id: 1, quantity: "200", note: "For the sauce", ...}) // "1--200%%For the sauce"
    • Private

      Decodes ingredients from a recipe's encoded ingredient string

      Parses the encoded ingredient string from a recipe, looking up each ingredient by ID in the database and combining it with the recipe-specific quantities and optional usage notes. Also calculates the combined seasonal availability.

      Supports both old format (without notes) and new format (with notes):

      • Old: "1--250__2--100" (backward compatible)
      • New: "1--250%%For sauce__2--100%%For garnish"

      Parameters

      • encodedIngredient: string

        Encoded string containing ingredient IDs, quantities, and optional notes

      • indexes: decodeIndexes

        Decode indexes providing the cached ingredients and collecting unresolved ids

      Returns [ingredientTableElement[], string[]]

      Tuple of [decoded ingredients array, combined season array]

      // Old format (backward compatible)
      Input: "1--250__2--100"
      Output: [[ingredient1 with quantity 250, ingredient2 with quantity 100], ["5","6","7"]]

      // New format with notes
      Input: "1--200%%For sauce__1--100%%For garnish"
      Output: [[ingredient1 with quantity 200 and note "For sauce", ingredient1 with quantity 100 and note "For garnish"], ...]
    • Private

      Computes the seasonal availability of a recipe from its ingredients

      Intersects the seasons of every ingredient the recipe uses. A recipe with no resolvable ingredients is available all year.

      Parameters

      Returns string[]

      Months during which every ingredient is available

    • Private

      Encodes a single ingredient for database storage

      Converts an ingredient element from application format into the encoded format required for database insertion. Joins seasonal data into a string representation using the encoding separator.

      Parameters

      Returns encodedIngredientElement

      Encoded ingredient ready for database storage

      Input: {id: 1, name: "Flour", unit: "g", type: "grain", season: ["1","2","3","12"]}
      Output: {"ID":1,"INGREDIENT":"Flour","UNIT":"g", "TYPE":"grain", "SEASON":"1__2__3__12"}
    • Private

      Encodes a single tag for database storage

      Converts a tag element from application format into the encoded format required for database insertion.

      Parameters

      • tag: TagDraft

        The tag object in application format

      Returns encodedTagElement

      Encoded tag ready for database storage

      Input: {id: 1, name: "Dessert"}
      Output: {"ID":1,"NAME":"Dessert"}
    • Private

      Decodes a single ingredient from database storage format

      Converts an encoded ingredient element from the database into the application format, parsing the seasonal data from its encoded string representation.

      Parameters

      Returns ingredientTableElement

      Decoded ingredient object in application format

      Input: {"ID":1,"INGREDIENT":"Flour","UNIT":"g", "TYPE":"grain", "SEASON":"1__2__3__12"}
      Output: {id: 1, name: "Flour", unit: "g", type: "grain", season: ["1","2","3","12"]}
    • Private

      Reports rows sharing a database id within a cached table

      Recipe decoding resolves ingredient and tag references through id-keyed maps built over these caches, so two rows with the same id silently shadow one another and every recipe referencing that id gets whichever row was indexed last. Cheap to detect while the table is already in hand.

      Parameters

      • elements: { id: number }[]

        Decoded rows of a cached table

      • label: string

        Table name used in the log and error message

      Returns void

    • Private

      Calculates the intersection of two seasonal availability arrays

      Combines seasonal data from multiple ingredients to determine when a recipe can be made using seasonal ingredients. Returns months that are common to both seasons.

      Parameters

      • previousSeason: string[]

        Previously calculated season array (accumulated from other ingredients)

      • ingredientSeason: string[]

        Season array from current ingredient

      Returns string[]

      Array of month strings that are available in both seasons

      Input: ["5","6","7","8"], ["6","7","8","9"]
      Output: ["6","7","8"]
    • Private

      Encodes a tag for storage within a recipe's tags list

      Converts a tag to its database ID string representation for storage within recipe data. Looks up the tag in the local cache if ID is missing.

      Parameters

      • tag: TagDraft

        The tag object to encode

      Returns string

      String representation of the tag's database ID

      Error if the tag cannot be resolved in the database

    • Private

      Decodes tags from a recipe's encoded tag string

      Parses the encoded tag string from a recipe, looking up each tag by ID in the cached tags to get the full tag information including names.

      Parameters

      • encodedTag: string

        Encoded string containing tag IDs separated by encoding separators

      • indexes: decodeIndexes

        Decode indexes providing the cached tags and collecting unresolved ids

      Returns tagTableElement[]

      Array of decoded tag objects

      Input: "1__2__5__3__4"
      Output: [{id: 1, name: "Italian"}, {id: 2, name: "Dinner"}, ...]
    • Private

      Decodes an array of tags from database storage format

      Processes multiple encoded tag elements from database queries, converting each one to the application format. Returns empty array if input is null, undefined, or empty.

      Parameters

      Returns tagTableElement[]

      Array of decoded tag objects in application format

    • Private

      Encodes nutrition information for database storage

      Converts a nutrition object to a string representation by joining all nutritional values with text separators for compact storage within recipe data.

      Parameters

      Returns string

      String representation of all nutrition values separated by text separators

    • Private

      Decodes nutrition information from database storage format

      Parses an encoded nutrition string back into a nutrition object. Returns undefined if the string is empty or has invalid format.

      Parameters

      • encodedNutrition: string

        Encoded string containing nutrition values separated by text separators

      Returns nutritionTableElement | undefined

      Decoded nutrition object or undefined if invalid/empty

      Input: "0--250--1046--15.0--8.0--25.0--12.0--2.5--6.0--0.8--100"
      Output: {id: undefined, energyKcal: 250, energyKj: 1046, fat: 15.0, ...}
    • Private

      Decodes preparation steps from database storage format

      Parses an encoded preparation string back into an array of preparation step objects. Each step can have both a title and description, or just a description.

      Parameters

      • encodedPreparation: string

        Encoded string containing preparation steps

      Returns preparationStepElement[]

      Array of preparation step objects with title and description

      Input: "Cook pasta--Boil water and add pasta__Mix sauce--Combine ingredients"
      Output: [{title: "Cook pasta", description: "Boil water and add pasta"}, {title: "Mix sauce", description: "Combine ingredients"}]
    • Private

      Retrieves all recipes from the database

      Fetches all recipe records from the database and decodes them into the application format for use in the local cache. Embedded ingredients and tags are resolved from the in-memory caches, which must already be loaded.

      Returns Promise<recipeTableElement[]>

      Promise resolving to array of all recipes in application format

    • Private

      Retrieves all tags from the database

      Fetches all tag records from the database and decodes them into the application format for use in the local cache.

      Returns Promise<tagTableElement[]>

      Promise resolving to array of all tags in application format

    • Private

      Retrieves all menu items from the database

      Fetches all menu records from the database and decodes them into the application format for use in the local cache.

      Returns Promise<menuTableElement[]>

      Promise resolving to array of all menu items in application format

    • Private

      Decodes an array of menu items from database storage format

      Processes multiple encoded menu elements from database queries, converting each one to the application format. Returns empty array if input is null, undefined, or empty.

      Parameters

      Returns menuTableElement[]

      Array of decoded menu items in application format

    • Private

      Reports menu rows pointing at a recipe that no longer exists

      Menu rows keep only a recipe id, resolved against the recipe cache when the menu is rendered. A row whose recipe was deleted therefore renders as an empty entry rather than failing outright, so it is surfaced here instead.

      Checked against the caches rather than inside the menu decoder, because both sides are plain cached data — decoding a menu row cannot see the recipes. Resolved from the cache, so it costs no query.

      Returns void

    • Private

      Compares two ingredient lists for similarity

      Determines if two ingredient lists are similar by comparing both ingredient names and quantities per person. Uses a 20% threshold for quantity differences. Used in the similar recipes feature to find recipes with comparable ingredients.

      Parameters

      Returns boolean

      True if ingredients lists are similar, false otherwise

      Two recipes with "flour: 2 cups per person" and "flour: 2.1 cups per person" would be similar
      Two recipes with "flour: 2 cups per person" and "flour: 3 cups per person" would not be similar (50% difference > 20% threshold)
    • Private

      Migrates the database to add source tracking columns if they don't exist

      This migration adds SOURCE_URL and SOURCE_PROVIDER columns to the recipes table to support bulk import tracking. Runs safely even if columns already exist.

      Returns Promise<void>