52 lines
1.7 KiB
JavaScript
52 lines
1.7 KiB
JavaScript
|
class PersonsManager {
|
||
|
|
||
|
constructor(baseUrl) {
|
||
|
this.baseUrl = baseUrl;
|
||
|
}
|
||
|
|
||
|
createPerson(name, age) {
|
||
|
fetch(`${this.baseUrl}/persons/`, {
|
||
|
method: 'POST',
|
||
|
headers: {
|
||
|
'Content-Type': 'application/json',
|
||
|
},
|
||
|
body: JSON.stringify({ name, age }),
|
||
|
})
|
||
|
.then(response => response.json())
|
||
|
.then(data => {
|
||
|
console.log('Person created:', data);
|
||
|
alert('Person created successfully!');
|
||
|
this.fetchPersons(); // Refresh the list after creating a person
|
||
|
})
|
||
|
.catch((error) => {
|
||
|
console.error('Error:', error);
|
||
|
});
|
||
|
}
|
||
|
|
||
|
fetchPersons(skip = 0, limit = 100) {
|
||
|
fetch(`${this.baseUrl}/persons/?skip=${skip}&limit=${limit}`)
|
||
|
.then(response => response.json())
|
||
|
.then(data => {
|
||
|
const personsList = document.getElementById('persons-list');
|
||
|
personsList.innerHTML = '<ul>' + data.map(person => `<li>${person.id} - ${person.name}, ${person.age} years old</li>`).join('') + '</ul>';
|
||
|
})
|
||
|
.catch((error) => {
|
||
|
console.error('Error:', error);
|
||
|
});
|
||
|
}
|
||
|
}
|
||
|
|
||
|
// Initialize the PersonsManager with the API base URL
|
||
|
const personsManager = new PersonsManager('http://localhost:9999');
|
||
|
|
||
|
document.getElementById('create-person-form').addEventListener('submit', function(e) {
|
||
|
e.preventDefault();
|
||
|
const name = document.getElementById('name').value;
|
||
|
const age = parseInt(document.getElementById('age').value, 10);
|
||
|
personsManager.createPerson(name, age);
|
||
|
});
|
||
|
|
||
|
document.getElementById('fetch-persons').addEventListener('click', function() {
|
||
|
personsManager.fetchPersons();
|
||
|
});
|