Files
RecipesCam/src/utils/storageUtils.ts
T

43 lines
1.5 KiB
TypeScript

import AsyncStorage from '@react-native-async-storage/async-storage';
import { Recipe } from '../types';
import { DEFAULT_RECIPES, DEFAULT_ADJUSTMENTS } from './defaultRecipes';
const CUSTOM_RECIPES_KEY = '@camrecipe_pro:custom_recipes';
export async function getCustomRecipes(): Promise<Recipe[]> {
try {
const data = await AsyncStorage.getItem(CUSTOM_RECIPES_KEY);
if (!data) return [];
return JSON.parse(data);
} catch (error) {
console.error('Failed to load custom recipes:', error);
return [];
}
}
export async function getAllRecipes(): Promise<Recipe[]> {
const custom = await getCustomRecipes();
// Backfill newer adjustment fields onto recipes persisted before they existed.
const fill = (r: Recipe): Recipe => ({ ...r, adjustments: { ...DEFAULT_ADJUSTMENTS, ...r.adjustments } });
return [...DEFAULT_RECIPES.map(fill), ...custom.map(fill)];
}
export async function saveCustomRecipe(recipe: Omit<Recipe, 'id' | 'isCustom'>): Promise<Recipe> {
const custom = await getCustomRecipes();
const newRecipe: Recipe = {
...recipe,
id: `custom_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
isCustom: true,
};
const updated = [...custom, newRecipe];
await AsyncStorage.setItem(CUSTOM_RECIPES_KEY, JSON.stringify(updated));
return newRecipe;
}
export async function deleteCustomRecipe(id: string): Promise<void> {
const custom = await getCustomRecipes();
const updated = custom.filter(r => r.id !== id);
await AsyncStorage.setItem(CUSTOM_RECIPES_KEY, JSON.stringify(updated));
}