From bd714ac05271e583d883ce9ef986039447538316 Mon Sep 17 00:00:00 2001 From: homsi6313-art Date: Wed, 18 Mar 2026 21:04:27 +0100 Subject: [PATCH] mustafa Refactor cocktail.js to generate markdown output --- task-1/cocktail.js | 64 +++++++++++++++++++++++++++++++++++++++------- 1 file changed, 55 insertions(+), 9 deletions(-) diff --git a/task-1/cocktail.js b/task-1/cocktail.js index 6fd5a62..292aec4 100644 --- a/task-1/cocktail.js +++ b/task-1/cocktail.js @@ -1,10 +1,41 @@ -// API documentation: https://www.thecocktaildb.com/api.php - import path from 'path'; +import { writeFile } from 'fs/promises'; const BASE_URL = 'https://www.thecocktaildb.com/api/json/v1/1'; -// Add helper functions as needed here +function generateMarkdown(drinks) { + let markdown = '# Cocktail Recipes\n\n'; + + for (const drink of drinks) { + markdown += ## ${drink.strDrink}\n\n; + + if (drink.strDrinkThumb) { + markdown += ![${drink.strDrink}](${drink.strDrinkThumb}/medium)\n\n; + } + + markdown += **Category**: ${drink.strCategory}\n\n; + markdown += **Alcoholic**: ${drink.strAlcoholic === 'Alcoholic' ? 'Yes' : 'No'}\n\n; + + markdown += ### Ingredients\n; + + for (let i = 1; i <= 15; i++) { + const ingredient = drink[strIngredient${i}]; + const measure = drink[strMeasure${i}]; + + if (!ingredient) break; + + markdown += - ${measure ? measure.trim() + ' ' : ''}${ingredient}\n; + } + + markdown += \n; + markdown += ### Instructions\n; + markdown += ${drink.strInstructions}\n\n; + markdown += Serve in: ${drink.strGlass}\n\n; + markdown += ---\n\n; + } + + return markdown; +} export async function main() { if (process.argv.length < 3) { @@ -13,17 +44,32 @@ export async function main() { } const cocktailName = process.argv[2]; - const url = `${BASE_URL}/search.php?s=${cocktailName}`; + const url = ${BASE_URL}/search.php?s=${cocktailName}; const __dirname = import.meta.dirname; - const outPath = path.join(__dirname, `./output/${cocktailName}.md`); + const outPath = path.join(__dirname, ./output/${cocktailName}.md); try { - // 1. Fetch data from the API at the given URL - // 2. Generate markdown content to match the examples - // 3. Write the generated content to a markdown file as given by outPath + const response = await fetch(url); + + if (!response.ok) { + throw new Error(HTTP error! status: ${response.status}); + } + + const data = await response.json(); + + if (!data.drinks) { + console.error('No cocktails found with that name.'); + await writeFile(outPath, # No results found for "${cocktailName}"); + return; + } + + const markdown = generateMarkdown(data.drinks); + + await writeFile(outPath, markdown); + console.log(File created at ${outPath}); } catch (error) { - // 4. Handle errors + console.error('Something went wrong:', error.message); } }