diff --git a/src/pages/PizzaForm.js b/src/pages/PizzaForm.js index 60c977fe4e5e95518549251c61e8021b0d06360f..fbcdfcc97fbe70f3aca589f3ab087098a9149254 100644 --- a/src/pages/PizzaForm.js +++ b/src/pages/PizzaForm.js @@ -1,3 +1,4 @@ +import Router from '../Router.js'; import Page from './Page.js'; export default class AddPizzaPage extends Page { @@ -8,6 +9,19 @@ export default class AddPizzaPage extends Page { Nom : <input type="text" name="name"> </label> + <label> + Image :<br/> + <input type="text" name="image" placeholder="https://source.unsplash.com/xxxxxxx/600x600"> + <small>Vous pouvez trouver des images de pizza sur <a href="https://unsplash.com/">https://unsplash.com/</a> puis utiliser l'URL <code>https://source.unsplash.com/xxxxxxx/600x600</code> où <code>xxxxxxx</code> est l'id de la photo choisie (celui dans la barre d'adresse)</small> + </label> + <label> + Prix petit format : + <input type="number" name="price_small" step="0.05"> + </label> + <label> + Prix grand format : + <input type="number" name="price_large" step="0.05"> + </label> <button type="submit">Ajouter</button> </form>`; } @@ -20,16 +34,43 @@ export default class AddPizzaPage extends Page { this.submit(); }); } + selector(inputName) { + const theInput = this.element.querySelector(`input[name="${inputName}"]`); + if (theInput === '') { + alert(`Erreur : le champ ${inputName} est obligatoire`); + return false; + } + return theInput.value; + } submit() { // D.4. La validation de la saisie - const nameInput = this.element.querySelector('input[name="name"]'), - name = nameInput.value; - if (name === '') { - alert('Erreur : le champ "Nom" est obligatoire'); - return; + const name = this.selector('name'); + const image = this.selector('image'); + const price_small = this.selector('price_small'); + const price_large = this.selector('price_large'); + if (name && image && price_large && price_small) { + const pizza = { + name, + image, + price_small, + price_large, + }; + fetch('http://localhost:8080/api/v1/pizzas', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(pizza), + }) + .then(response => { + if (response.ok) { + alert(`La pizza ${name} a été ajoutée !`); + this.element.querySelector('input[name="name"]').value = ''; + Router.navigate('/', true); + } else { + throw new Error(); + } + }) + .catch(err => alert('Erreur')); } - alert(`La pizza ${name} a été ajoutée !`); - nameInput.value = ''; } }