Skip to content

Instantly share code, notes, and snippets.

@FazioNico
Last active December 1, 2020 16:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FazioNico/4d614af25626c9c020d9ae24f04e50d1 to your computer and use it in GitHub Desktop.
Save FazioNico/4d614af25626c9c020d9ae24f04e50d1 to your computer and use it in GitHub Desktop.
[For Student]: Build Simple CFF Timetable Application
/**
* EXO FETCH et MANIPULATION DES DONNÉES
* DOC API: https://timetable.search.ch/api/help.en.html
* */
// APPLICATION CFF SIMPLE:
const buildSearchHTML = () => {
const contener = document.querySelector('#cffApp');
contener.innerHTML = `
<input id="from" type="text" />
<input id="to" type="text" />
<button id="search">search</button>
`;
}
const addEventUI = () => {
const btnSearch = document.querySelector('#search');
btnSearch.addEventListener('click', async (event)=> {
// 3: récupérer les valeur du formulaire
const values = getFormValues();
// 4: faire une requête à l'API et récupérer la réponse
const response = await requestFromTo(values);
// 5: construire le HTML final avec la réponse
buildResponseHTML(response.connections)
})
}
const getFormValues = () => {
const from = document.querySelector('#from').value;
const to = document.querySelector('#to').value;
return {from, to};
}
const requestFromTo = (datas) => {
return fetch(`https://timetable.search.ch/api/route.en.json?from=${datas.from}&to=${datas.to}`).then(response => response.json());
}
const buildResponseHTML = (connections) => {
console.log('response ->', connections);
const contener = document.querySelector('#cffApp');
contener.innerHTML = `
<ul>
${connections.map(conn => {
return `<li>
De ${conn.from}: ${new Date(conn.departure).toLocaleTimeString()} à ${conn.to}: ${new Date(conn.arrival).toLocaleTimeString()}
${(conn.legs.length > 0) ? displayLegs(conn.legs) : ''}
</li>`;
}).join('')}
</ul>
`;
}
const displayLegs = (legs) => {
return `
<ul>${legs.map(l => {
return `<li>${l.name}: ${l.line}</li>`;
}).join('')}</ul>
`;
}
const cffApp = () => {
console.log('run cffApp...');
// 1: créer formulaire de recherche
buildSearchHTML();
// 2: ajouter la gestion des events
// -> click sur btn search
addEventUI();
}
cffApp();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment