transporter-app/services/api.js

98 lines
3.1 KiB
JavaScript
Raw Permalink Normal View History

2024-06-26 23:24:26 +03:00
import axios from "axios";
import Database from "../db";
import ConnectionStore from "../store/connectionStore";
import {increaseNewTaskBadge} from "../store/taskStore";
import {increaseNewNotificationBadge} from "../store/notificationStore";
class API {
constructor() {
this.instance = axios.create({baseURL: "http://10.2.101.91:8000/api/v1", headers: {"Content-Type": "application/json"}})
}
async getAndPutIntoDB({endpoint, prefix, badge}) {
try {
const {data} = await this.instance.get(endpoint)
ConnectionStore.internet = true
const ids = []
data.forEach(elem => {
typeof badge !== 'undefined' && !Database.contains(`${prefix}.${elem.id}`) && badge()
ids.push(elem.id)
Database.set(`${prefix}.${elem.id}`, JSON.stringify(elem))
})
Database.getAllKeys().forEach(key => {
if (!key.startsWith(`${prefix}.`)) {
return
}
if (!ids.includes(+(key.split('.')[1]))) {
Database.delete(key)
}
})
} catch (e) {
ConnectionStore.internet = false
}
}
async getTasks() {
await this.getAndPutIntoDB({endpoint: "/tasks", prefix: "task", badge: increaseNewTaskBadge})
}
async getSubTasks() {
await this.getAndPutIntoDB({endpoint: "/subtasks/all", prefix: "subtask"})
}
async getNotifications() {
// TODO UPDATE FROM LOCAL BEFORE GETTING VALUES
await this.getAndPutIntoDB({
endpoint: "/notifications",
prefix: "notification",
badge: increaseNewNotificationBadge
})
}
async getEvents() {
await this.getAndPutIntoDB({endpoint: '/events', prefix: "event"})
}
async getEventsTask() {
await this.getAndPutIntoDB({endpoint: '/events/tasks', prefix: 'tevents_task'})
}
async completeSubTask(subtaskId) {
const {data} = await this.instance.post(`/subtasks/${subtaskId}/complete`, {subtaskId})
}
async setNotificationsRecited({notificationIds}) {
notificationIds.forEach(elem => {
Database.set(`notification.${elem}`, JSON.stringify({
...JSON.parse(Database.getString(`notification.${elem}`)),
is_recited: true
}))
})
try {
await this.instance.post('/notifications/recited', {
notification_ids:
notificationIds
})
ConnectionStore.internet = true
} catch (e) {
ConnectionStore.internet = false
// TODO UPDATE BEFORE GETTING VALUES
// Database.set(`shouldupdate.notification`, JSON.stringify(notificationIds))
}
}
async createNewEvent({task_id, event_id}) {
Database.set(`tevents_task.${event_id}`, JSON.stringify({...JSON.parse(Database.getString(`event.${event_id}`)), task_id: task_id, is_completed: false}))
await this.instance.post('/events', {task_id, event_id})
}
}
export default new API()