import '../../../core/api/api_client.dart'; import '../../../core/api/api_exception.dart'; import '../domain/parsed_recipe.dart'; import '../domain/recipe.dart'; class RecipeRepository { final ApiClient _api; RecipeRepository(this._api); Future> fetchRecipes({String? token}) async { try { final data = await _api.getJson('/recipes', token: token); if (data is! List) { throw const ApiException( type: ApiErrorType.unknown, message: 'Ogiltigt svar fran servern.'); } return data .map((e) => Recipe.fromJson(e as Map)) .toList(); } on ApiException { rethrow; } catch (_) { throw const ApiException( type: ApiErrorType.network, message: 'Kunde inte hamta recept.'); } } Future fetchRecipeDetail(int id, {String? token}) async { try { final data = await _api.getJson('/recipes/$id', token: token); if (data is! Map) { throw const ApiException( type: ApiErrorType.unknown, message: 'Ogiltigt svar fran servern.'); } return Recipe.fromJson(data); } on ApiException { rethrow; } catch (_) { throw const ApiException( type: ApiErrorType.network, message: 'Kunde inte hamta recept.'); } } Future createRecipe(Map body, {String? token}) async { try { final data = await _api.postJson('/recipes', body: body, token: token); if (data is! Map) { throw const ApiException( type: ApiErrorType.unknown, message: 'Ogiltigt svar fran servern.'); } return Recipe.fromJson(data); } on ApiException { rethrow; } catch (_) { throw const ApiException( type: ApiErrorType.network, message: 'Kunde inte spara recept.'); } } Future updateRecipe(int id, Map body, {String? token}) async { try { final data = await _api.patchJson('/recipes/$id', body: body, token: token); if (data is! Map) { throw const ApiException( type: ApiErrorType.unknown, message: 'Ogiltigt svar fran servern.'); } return Recipe.fromJson(data); } on ApiException { rethrow; } catch (_) { throw const ApiException( type: ApiErrorType.network, message: 'Kunde inte uppdatera recept.'); } } Future deleteRecipe(int id, {String? token}) async { try { await _api.deleteJson('/recipes/$id', token: token); } on ApiException { rethrow; } catch (_) { throw const ApiException( type: ApiErrorType.network, message: 'Kunde inte ta bort recept.'); } } Future parseMarkdown(String markdown, {String? token}) async { try { final data = await _api.postJson( '/recipes/parse-markdown', body: {'markdown': markdown}, token: token, ); if (data is! Map) { throw const ApiException( type: ApiErrorType.unknown, message: 'Ogiltigt svar fran servern.'); } return ParsedRecipe.fromJson(data); } on ApiException { rethrow; } catch (_) { throw const ApiException( type: ApiErrorType.network, message: 'Kunde inte tolka receptet.'); } } }