diff --git a/javascript/JS_Esercizi 11 - API/01_get_singolo_utente/script.js b/javascript/JS_Esercizi 11 - API/01_get_singolo_utente/script.js index 4548770..d5eb043 100644 --- a/javascript/JS_Esercizi 11 - API/01_get_singolo_utente/script.js +++ b/javascript/JS_Esercizi 11 - API/01_get_singolo_utente/script.js @@ -80,11 +80,12 @@ function handleError(message) { * 2. Controlla che l'ID sia valido, ovvero un numero tra 1 e 40 * In caso contrario, mostra un messaggio di errore (usa handleError()) e return * 3. Mostra lo spinner di caricamento (rimuovi la classe nascosto) - * 4. Fai una fetch GET a /users/{id} - * 5. Se la risposta non è OK, usa handleError() per mostrare un messaggio e return - * 6. Converti la risposta in JSON - * 7. Mostra i dati dell'utente chiamando createUserCard(user) - * 8. Nascondi lo spinner di caricamento (aggiungi la classe nascosto) + * 4. Apri un blocco try/catch + * 5. Fai una fetch GET a /users/{id} + * 6. Se la risposta non è OK, usa handleError() per mostrare un messaggio e return + * 7. Converti la risposta in JSON + * 8. Mostra i dati dell'utente chiamando createUserCard(user) + * 9. Nascondi lo spinner di caricamento (aggiungi la classe nascosto) */ async function fetchUser() { // TODO Rimuovi questa riga e completa la funzione diff --git a/javascript/JS_Esercizi 11 - API/02_get_lista_utenti/script.js b/javascript/JS_Esercizi 11 - API/02_get_lista_utenti/script.js index cc7e50b..a35c758 100644 --- a/javascript/JS_Esercizi 11 - API/02_get_lista_utenti/script.js +++ b/javascript/JS_Esercizi 11 - API/02_get_lista_utenti/script.js @@ -55,11 +55,12 @@ function handleError(message) { * * Passi: * 1. Mostra lo spinner di caricamento (rimuovi la classe nascosto) - * 2. Fai una fetch GET a /users - * 3. Se la risposta non è OK, usa handleError() per mostrare un messaggio e return - * 4. Converti la risposta da stringa JSON a oggetto JavaScript - * 5. Mostra i dati degli utenti chiamando mostraUtenti(users) - * 6. Nascondi lo spinner di caricamento (aggiungi la classe nascosto) + * 2. Apri un blocco try/catch + * 3. Fai una fetch GET a /users + * 4. Se la risposta non è OK, usa handleError() per mostrare un messaggio e return + * 5. Converti la risposta da stringa JSON a oggetto JavaScript + * 6. Mostra i dati degli utenti chiamando mostraUtenti(users) + * 7. Nascondi lo spinner di caricamento (aggiungi la classe nascosto) */ async function fetchAllUsers() { // TODO Rimuovi questa riga e completa la funzione diff --git a/javascript/JS_Esercizi 11 - API/03_utente_e_post/script.js b/javascript/JS_Esercizi 11 - API/03_utente_e_post/script.js index 98a0e86..f8d0f38 100644 --- a/javascript/JS_Esercizi 11 - API/03_utente_e_post/script.js +++ b/javascript/JS_Esercizi 11 - API/03_utente_e_post/script.js @@ -1,74 +1,30 @@ -// ⚠️ COMPILARE PRIMA DI INIZIARE +// ⚠️ COMPILARE E CONTROLLARE PRIMA DI INIZIARE ⚠️ const BASE_URL = 'http://localhost:3000/api'; +const userId = document.getElementById('userId'); +const loading = document.getElementById('loading'); +const userProfile = document.getElementById('userProfile'); +const postsContainer = document.getElementById('postsContainer'); +const btnFetch = document.getElementById('btnFetch'); + /** - * ESERCIZIO 3: Recupera un utente E tutti i suoi post + * FUNZIONE: Crea un utente card * - * Devi completare questa funzione: - * 1. Leggi l'ID dell'utente - * 2. Fai DUE fetch: - * - GET /users/{id} - * - GET /posts - * 3. Filtra i post per trovare solo quelli di questo utente (usando userId) - * 4. Mostra i risultati - * 5. Gestisci gli errori + * Crea la card completa dell'utente e la inserisce nell'elemento userProfile + * L'oggetto user ha questa struttura: + * { + * id: number, + * nome: string, + * cognome: string, + * email: string, + * avatar: string (url), + * dataNascita: string (formato YYYY-MM-DD), + * comune: string, + * attivo: boolean + * } */ -async function fetchUserAndPosts() { - const userId = document.getElementById('userId').value; - const loading = document.getElementById('loading'); - const userProfile = document.getElementById('userProfile'); - const postsContainer = document.getElementById('postsContainer'); - - if (!userId || userId < 1 || userId > 40) { - userProfile.innerHTML = '
❌ Inserisci un ID valido tra 1 e 40
'; - return; - } - - loading.style.display = 'block'; - userProfile.innerHTML = ''; - postsContainer.innerHTML = ''; - - try { - // 👇 SCRIVI QUI IL TUO CODICE 👇 - // 1. Fetch utente - // const userResponse = await fetch(...); - // const user = await userResponse.json(); - - // 2. Fetch tutti i post - // const postsResponse = await fetch(...); - // const allPosts = await postsResponse.json(); - - // 3. Filtra i post di questo utente - // const userPosts = allPosts.filter(post => post.userId === user.id); - - // 4. Visualizza - // displayUserWithPosts(user, userPosts); - - // PLACEHOLDER - Rimuovi questa riga quando completi - throw new Error('Codice non implementato - Completa la funzione fetchUserAndPosts()'); - - } catch (error) { - userProfile.innerHTML = ` -
- ❌ Errore: ${error.message} -
- `; - console.error('Errore:', error); - } finally { - loading.style.display = 'none'; - } -} - -/** - * Visualizza utente e post - * (Questa funzione è già fatta - non modificare) - */ -function displayUserWithPosts(user, posts) { - const userProfile = document.getElementById('userProfile'); - const postsContainer = document.getElementById('postsContainer'); - - // CARD UTENTE - const userHTML = ` +function creaCardUtente(user) { + userProfile.innerHTML = `
Avatar @@ -80,45 +36,94 @@ function displayUserWithPosts(user, posts) {
`; - - userProfile.innerHTML = userHTML; - - // POST DELL'UTENTE - if (!posts || posts.length === 0) { - postsContainer.innerHTML = ` -
-

📄 Post (0)

-
Questo utente non ha scritto nessun post
-
- `; - return; - } - - const postsHTML = ` -
-

📄 Post (${posts.length})

- ${posts.map(post => ` -
-
-

${post.titolo}

- -
-

${post.contenuto}

- -
- `).join('')} -
- `; - - postsContainer.innerHTML = postsHTML; } + +/** + * FUNZIONE: Crea le card dei post + * + * Visualizza i post dell'utente nel contenitore postsContainer + * Se non ci sono post, mostra un messaggio di vuoto + * posts è un array di oggetti con questa struttura: + * { + * id: number, + * userId: number, + * titolo: string, + * contenuto: string, + * data: string (formato YYYY-MM-DD), + * likes: number + * } + */ +function creaCardPosts(postList) { + + let allPosts = postList.map((post) => ` +
+
+

${post.titolo}

+ +
+

${post.contenuto}

+
+ +
+
+ `).join('') + + if (postList.length === 0) { + allPosts = ` +
+ Questo utente non ha scritto nessun post +
+ `; + } + + postsContainer.innerHTML = ` +
+

📄 Post (${postList.length})

+ ${allPosts} +
+ `; +} + +/** + * FUNZIONE: Gestione errori + * + * Mostra un messaggio di errore e logga in console + */ +function handleError(message) { + userProfile.innerHTML = ` +
+ ❌ ${message} +
+ `; + console.error('Errore:', message); +} + + +/** + * ESERCIZIO 3: Recupera un utente E tutti i suoi post + * + * Devi completare questa funzione: + * 1. Leggi l'ID dell'utente + * 2. Valida che sia un numero tra 1 e 40 + * 3. Mostra lo spinner di caricamento + * 4. Apri un blocco try/catch + * 5. Fai DUE fetch: + * - GET /users/{id} + * - GET /posts + * 6. Filtra i post per trovare solo quelli di questo utente (usando userId) + * - Il filtro va fatto in JS, ma puoi anche usare un endpoint come /posts?userId={id} + * 7. Mostra i risultati chiamando prima creaCardUtente(user) e poi creaCardPosts(posts) + * 8. Gestisci gli errori con handleError() + */ +async function fetchUserAndPosts() { +} + + // COLLEGA IL BOTTONE -document.getElementById('btnFetch').addEventListener('click', fetchUserAndPosts); +btnFetch.addEventListener('click', fetchUserAndPosts); // PERMETTI ENTER -document.getElementById('userId').addEventListener('keypress', (e) => { +userId.addEventListener('keypress', (e) => { if (e.key === 'Enter') fetchUserAndPosts(); }); diff --git a/javascript/JS_Esercizi 11 - API/index.html b/javascript/JS_Esercizi 11 - API/index.html index 5d1117e..8f8badd 100644 --- a/javascript/JS_Esercizi 11 - API/index.html +++ b/javascript/JS_Esercizi 11 - API/index.html @@ -172,7 +172,7 @@

API REST

-

Esercizi Semplificati - Da Base a CRUD

+

Esercizi Da Base a CRUD

Tutorial Introduttivo