chore: refactor to remove duplication - patch requests

issue #46

From now on, only a single patchJSON function will be used to call the backend api. No more duplications
This commit is contained in:
2024-09-21 18:10:52 -03:00
parent 1b7d32b27d
commit d19677ad14
6 changed files with 34 additions and 86 deletions
+24 -3
View File
@@ -2,6 +2,9 @@ import { API_TOKEN } from '../app-constants/app-constants';
const tokenState = localStorage.getItem(API_TOKEN);
/**
*
*/
function handleError(httpStatusCode: number) {
if (httpStatusCode === 403) {
throw new Error('Forbidden! Access denied');
@@ -25,10 +28,28 @@ const api = {
if (response.ok) {
const data = await response.json();
return data;
} else {
handleError(response.status);
}
handleError(response.status);
return false;
},
patchJSON: async (url: string, payload: object) => {
const response = await fetch(url, {
method: 'PATCH',
mode: 'cors',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${tokenState}`
},
body: JSON.stringify(payload)
});
if (response.ok) {
const data = await response.json();
return data;
}
handleError(response.status);
return false;
}
}
};
export default api;
-1
View File
@@ -1,6 +1,5 @@
import { API_TOKEN } from '../app-constants/app-constants';
import { SigninResponse } from '../types/SigninResponse';
import api from './api';
import ApiConfig from './apiConfig';
/**
+1 -43
View File
@@ -2,7 +2,6 @@ import { API_TOKEN } from '../app-constants/app-constants';
import TaskNoteRequest from '../types/TaskNoteRequest';
import { NoteResponse } from '../types/NoteResponse';
import ApiConfig from './apiConfig';
import api from './api';
/**
* Sends a POST request to the server to create a note.
@@ -44,47 +43,6 @@ async function addNoteRequest(note: TaskNoteRequest): Promise<NoteResponse> {
throw new Error('Unknown error');
}
/**
* Sends a PATCH request to the server to update a note.
*
* @param {NoteResponse} note - The note to be updated.
* @returns {Promise<undefined>} A promise that resolves to undefined if the deletion was
* successful.
* @throws {Error} An error object if there was an error
*/
async function updateNoteRequest(note: NoteResponse): Promise<undefined> {
try {
const tokenState = localStorage.getItem(API_TOKEN);
const response = await fetch(`${ApiConfig.notesUrl}/${note.id}`, {
method: 'PATCH',
mode: 'cors',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${tokenState}`
},
body: JSON.stringify({
title: note.title,
description: note.description
})
});
if (response.ok) {
await response.json();
return;
}
if (response.status === 403) {
throw new Error('Forbidden! Access denied');
}
if (response.status === 500) {
throw new Error('Internal Server Error!');
}
} catch (e) {
if (typeof e === 'string') {
throw new Error(e as string);
}
}
throw new Error('Unknown error');
}
/**
* Sends a DELETE request to the server to delete a note by its ID.
*
@@ -122,5 +80,5 @@ async function deleteNoteRequest(id: number): Promise<undefined> {
}
export {
addNoteRequest, updateNoteRequest, deleteNoteRequest
addNoteRequest, deleteNoteRequest
};
+1 -34
View File
@@ -39,39 +39,6 @@ async function addTaskRequest(task: TaskNoteRequest): Promise<TaskResponse | Err
throw new Error('Unknown error');
}
/**
*
*/
async function updateTaskDoneRequest(id: number, done: boolean): Promise<undefined> {
try {
const tokenState = localStorage.getItem(API_TOKEN);
const response = await fetch(`${ApiConfig.tasksUrl}/${id}`, {
method: 'PATCH',
mode: 'cors',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${tokenState}`
},
body: JSON.stringify({ done })
});
if (response.ok) {
await response.json();
return;
}
if (response.status === 403) {
throw new Error('Forbidden! Access denied');
}
if (response.status === 500) {
throw new Error('Internal Server Error!');
}
} catch (e) {
if (typeof e === 'string') {
throw new Error(e as string);
}
}
throw new Error('Unknown error');
}
/**
*
*/
@@ -104,5 +71,5 @@ async function deleteTaskRequest(id: number): Promise<undefined> {
}
export {
addTaskRequest, updateTaskDoneRequest, deleteTaskRequest
addTaskRequest, deleteTaskRequest
};
+2 -2
View File
@@ -7,7 +7,7 @@ import TaskNoteRequest from '../../types/TaskNoteRequest';
import { NoteResponse } from '../../types/NoteResponse';
import './style.css';
import {
addNoteRequest, deleteNoteRequest, updateNoteRequest
addNoteRequest, deleteNoteRequest
} from '../../api-service/noteService';
import api from '../../api-service/api';
import ApiConfig from '../../api-service/apiConfig';
@@ -60,7 +60,7 @@ function Note(): JSX.Element {
const submitEditNote = async (payload: NoteResponse): Promise<boolean> => {
try {
await updateNoteRequest(payload);
await api.patchJSON(`${ApiConfig.notesUrl}/${payload.id}`, payload);
loadNotes();
return true;
} catch (e) {
+6 -3
View File
@@ -4,8 +4,7 @@ import {
} from 'react-bootstrap';
import {
addTaskRequest,
deleteTaskRequest,
updateTaskDoneRequest
deleteTaskRequest
} from '../../api-service/taskService';
import TaskNoteRequest from '../../types/TaskNoteRequest';
import { TaskResponse } from '../../types/TaskResponse';
@@ -77,7 +76,11 @@ function Task(): JSX.Element {
const markAsDone = async (task: TaskResponse) => {
try {
await updateTaskDoneRequest(task.id, !task.done);
const updatedTask = {
...task,
done: !task.done
};
await api.patchJSON(`${ApiConfig.tasksUrl}/${task.id}`, updatedTask);
loadTasks();
} catch (e) {
handleError(e);