Commit 507f898e authored by Geovanny's avatar Geovanny

Added response check for api calls

parent 86b306ae
...@@ -17,7 +17,7 @@ class TaskController { ...@@ -17,7 +17,7 @@ class TaskController {
async createTask(){ async createTask(){
let new_task ={done: false, description: "New Task"} let new_task ={done: false, description: "New Task"}
try { try {
await this.create(new_task) new_task.id = await this.create(new_task)
this.addTask(new Task(new_task)) this.addTask(new Task(new_task))
} catch(error) { } catch(error) {
console.log(error) console.log(error)
...@@ -27,17 +27,26 @@ class TaskController { ...@@ -27,17 +27,26 @@ class TaskController {
addTask(task){ addTask(task){
this.view.addTaskView(task) this.view.addTaskView(task)
task.addEventListener("change", () => this.update(task)) task.addEventListener("change", async () => this.updateTask(task))
} }
remoteTask(task){ async remoteTask(task){
try{
await this.requestDelete(task)
this.tasks.remove(task) this.tasks.remove(task)
this.view.removeTaskView(task) this.view.removeTaskView(task)
this.requestDelete(task) } catch(error) {
console.log(error)
alert('Failed to delete task.')
}
} }
async refresh(){ async refresh(){
let tasks_response = await fetch("/tasks", {method: "GET"}) let tasks_response = await fetch("/tasks", {method: "GET"})
if(!tasks_response.ok){
throw new Error(`Got ${tasks_response.status} from server.`)
}
let tasks_data = await tasks_response.json() let tasks_data = await tasks_response.json()
for (let task_data of tasks_data){ this.tasks.push(new Task(task_data)) } for (let task_data of tasks_data){ this.tasks.push(new Task(task_data)) }
...@@ -58,8 +67,19 @@ class TaskController { ...@@ -58,8 +67,19 @@ class TaskController {
} }
let task_data = await tasks_response.json() let task_data = await tasks_response.json()
if(!task_data.id){
throw new Error('No task id created')
}
return task_data.id
}
return task_data async updateTask(task){
try{
await this.update(task)
} catch(error) {
console.log(error)
alert('Changes applied locally only')
}
} }
async update(task){ async update(task){
...@@ -70,12 +90,20 @@ class TaskController { ...@@ -70,12 +90,20 @@ class TaskController {
'Content-Type': 'application/json' 'Content-Type': 'application/json'
} }
}) })
if(!tasks_response.ok){
throw new Error(`Got ${tasks_response.status} from server.`)
}
} }
async requestDelete(task){ async requestDelete(task){
let tasks_response = await fetch(`/tasks/${task.id}`, { let tasks_response = await fetch(`/tasks/${task.id}`, {
method: "DELETE" method: "DELETE"
}) })
if(!tasks_response.ok){
throw new Error(`Got ${tasks_response.status} from server.`)
}
} }
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment