Skip to content

Commit 3402921

Browse files
committed
Refactor task retrieval and update methods
1 parent d2522b1 commit 3402921

File tree

1 file changed

+119
-61
lines changed

1 file changed

+119
-61
lines changed

src/helpers/task.ts

Lines changed: 119 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -236,37 +236,80 @@ export class Task {
236236
return JSON.parse(tasks);
237237
}
238238

239+
/// newly refactored
239240
async getTasksByCategoryPosition(position: number) {
240241
try {
241-
let tasks = null;
242-
let readfromfile = false;
243-
// if the lastTaskCategoryByPosition is less than 2 minutes, return the tasks
244-
let cacheLastUpdate = this.tasksCategoryList.getTaskLastUpdate(position);
245-
if (cacheLastUpdate && ((new Date().getTime() - cacheLastUpdate.getTime()) < (45 * 1000)) || !navigator.onLine) {
246-
// if (this.lastUpdate[position] && (new Date().getTime() - this.lastUpdate[position].getTime()) < (45 * 1000)) {
247-
tasks = await this.getTasksByCategoryPositionFromFile(position);
248-
readfromfile = true;
249-
}
250-
else if (navigator.onLine) {
251-
tasks = await this.getTasksByCategoryPositionFromApi(position);
252-
} else {
253-
tasks = await this.getTasksByCategoryPositionFromFile(position);
254-
readfromfile = true;
255-
}
256-
// this.tasksCategoryList[position] = { ...this.tasksCategoryList[position], tasks };
257-
let newTask = this.tasksCategoryList.get();
258-
newTask[position] = { ...newTask[position], tasks };
259-
this.tasksCategoryList.update(newTask);
260-
console.log(this.tasksCategoryList, "this.tasks", "after if");
261-
if(!readfromfile) await this.saveTasksToFile();
242+
const tasks = await this.retrieveTasksByCategoryPosition(position);
243+
this.updateTaskCategoryList(position, tasks);
244+
await this.saveTasksToFileIfNeeded(!tasks); // Save to file if tasks are not retrieved
262245
return tasks;
263246
} catch (error) {
264-
console.error("Error getting tasks by category position:", error);
247+
console.error("Error getting tasks by category position:", (error as Error).message);
265248
this.errorHandler(error as Error);
266249
return [];
267250
}
268251
}
269252

253+
/**
254+
* Updates the task category list with the retrieved tasks for a specific position.
255+
* @param {number} position - The position of the category.
256+
* @param {task[]} tasks - The list of tasks.
257+
*/
258+
updateTaskCategoryList(position: number, tasks: task[]) {
259+
const currentTaskList = this.tasksCategoryList.get();
260+
currentTaskList[position] = { ...currentTaskList[position], tasks };
261+
this.tasksCategoryList.update(currentTaskList);
262+
}
263+
264+
/**
265+
* Saves tasks to the local file if needed.
266+
* @param {boolean} condition - The condition to determine if saving is needed.
267+
*/
268+
async saveTasksToFileIfNeeded(condition: boolean) {
269+
if (condition) {
270+
await this.saveTasksToFile();
271+
}
272+
}
273+
274+
275+
276+
/**
277+
* Retrieves tasks by category position from either the API or the local file.
278+
* @param {number} position - The position of the category.
279+
* @returns {task[]} - The list of tasks.
280+
*/
281+
async retrieveTasksByCategoryPosition(position: number): Promise<task[]> {
282+
const cacheLastUpdate = this.tasksCategoryList.getTaskLastUpdate(position);
283+
const isCacheValid = cacheLastUpdate && ((new Date().getTime() - cacheLastUpdate.getTime()) < (45 * 1000)) || !navigator.onLine;
284+
285+
if (isCacheValid) {
286+
return await this.getTasksByCategoryPositionFromFile(position);
287+
} else if (navigator.onLine) {
288+
return await this.getTasksByCategoryPositionFromApi(position);
289+
} else {
290+
return await this.getTasksByCategoryPositionFromFile(position);
291+
}
292+
}
293+
294+
/**
295+
* Retrieves tasks by category ID from either the API or the local file.
296+
* @param {string} categoryID - The ID of the category.
297+
* @returns {task[]} - The list of tasks.
298+
*/
299+
async retrieveTasksByCategoryID(categoryID: string): Promise<task[]> {
300+
const cacheLastUpdate = this.tasksCategoryList.getTaskLastUpdate(categoryID);
301+
const isCacheValid = cacheLastUpdate && ((new Date().getTime() - cacheLastUpdate.getTime()) < (45 * 1000) || !navigator.onLine);
302+
303+
if (isCacheValid) {
304+
return await this.getTaskByIdFromFile(categoryID);
305+
} else if (navigator.onLine) {
306+
return await this.getTaskByIdFromApi(categoryID);
307+
} else {
308+
return await this.getTaskByIdFromFile(categoryID);
309+
}
310+
}
311+
312+
270313
async getTasksByCategoryPositionFromApi(position: number): Promise<task[]> {
271314
if(!navigator.onLine) throw new Error("No internet connection");
272315
const taskCategory = this.tasksCategoryList.get()[position];
@@ -277,61 +320,76 @@ export class Task {
277320
Authorization: `Bearer ${this.accessToken}`,
278321
},
279322
});
280-
const tasks: task[] = response.data.items.map((item: any) => {
281-
return {
282-
id: item.id,
283-
name: item.title,
284-
description: item.notes,
285-
dueDate: item.due,
286-
completed: item.status === "completed",
287-
};
288-
});
323+
const tasks: task[] = this.mapTasksFromApiResponse(response.data.items);
289324
this.tasksCategoryList.setTaskLastUpdate(position, new Date());
290325
return tasks;
291326
}
292327

328+
/**
329+
* Maps tasks from API response.
330+
* @param {object[]} apiResponseItems - The items from the API response.
331+
* @returns {task[]} - The mapped tasks.
332+
*/
333+
mapTasksFromApiResponse(apiResponseItems: object[]): task[] {
334+
return apiResponseItems.map((item: any) => ({
335+
id: item.id,
336+
name: item.title,
337+
description: item.notes,
338+
dueDate: item.due,
339+
completed: item.status === "completed",
340+
}));
341+
}
342+
343+
344+
/**
345+
* Gets tasks by category position from a local file.
346+
* @param {number} position - The position of the category.
347+
* @returns {task[]} - The list of tasks.
348+
*/
293349
async getTasksByCategoryPositionFromFile(position: number): Promise<task[]> {
294350
const tasks = await readTextFile(`tasks.json`, { dir: DEFAULT_DIRECTORY });
295351
const taskCategories = JSON.parse(tasks);
296-
console.log(taskCategories, "taskCategories");
297352
return taskCategories[position].tasks;
298353
}
299354

300-
async getTaskById(categoryID: string) {
355+
async getTasksByCategoryID(categoryID: string) {
301356
try {
302-
let task: task[] = []
303-
let readfromfile = false;
304-
305-
// if the lastTaskCategoryByPosition is less than 2 minutes, return the tasks
306-
let cacheLastUpdate = this.tasksCategoryList.getTaskLastUpdate(categoryID);
307-
if (cacheLastUpdate && ((new Date().getTime() - cacheLastUpdate.getTime()) < (45 * 1000) || !navigator.onLine)) {
308-
task = await this.getTaskByIdFromFile(categoryID);
309-
readfromfile = true;
310-
// console.log("from file", task);
311-
}
312-
// check if online and get tasks from api
313-
else if (navigator.onLine) {
314-
task = await this.getTaskByIdFromApi(categoryID);
315-
} else {
316-
task = await this.getTaskByIdFromFile(categoryID);
317-
readfromfile = true;
318-
}
319-
let newTask = this.tasksCategoryList.get().map((taskCategory) => {
320-
if (taskCategory.id === categoryID) {
321-
taskCategory.tasks = task;
322-
}
323-
return taskCategory;
324-
});
325-
this.tasksCategoryList.update(newTask);
326-
if(!readfromfile) await this.saveTasksToFile();
327-
return task;
357+
let tasks: task[] = [];
358+
let readFromFile = false;
359+
360+
tasks = await this.retrieveTasksByCategoryID(categoryID);
361+
362+
this.updateTaskCategoryTasks(categoryID, tasks);
363+
await this.saveTasksToFileIfNeeded(!readFromFile);
364+
365+
return tasks;
328366
} catch (error) {
329-
// console.error(error);
330367
this.errorHandler(error as Error);
331-
return null;
368+
return [];
332369
}
333370
}
334371

372+
/**
373+
* Updates the tasks for a specific task category.
374+
* @param {string} categoryID - The ID of the task category.
375+
* @param {task[]} tasks - The tasks to update.
376+
*/
377+
updateTaskCategoryTasks(categoryID: string, tasks: task[]) {
378+
const updatedTaskCategories = this.tasksCategoryList.get().map((taskCategory) => {
379+
if (taskCategory.id === categoryID) {
380+
taskCategory.tasks = tasks;
381+
}
382+
return taskCategory;
383+
});
384+
385+
this.tasksCategoryList.update(updatedTaskCategories);
386+
}
387+
388+
389+
390+
/// end of newly refactored
391+
392+
335393
async getTaskByIdFromApi(categoryID: string): Promise<task[]> {
336394
if(!navigator.onLine) throw new Error("No internet connection");
337395
const url = `${this.baseUrl}/lists/${categoryID}/tasks`;

0 commit comments

Comments
 (0)