juggl/juggl-server/js/api.js

116 lines
2.3 KiB
JavaScript
Raw Normal View History

2020-11-08 15:21:51 +01:00
API_URL = "/api";
const api = {
getProjects() {
return request("/getProjects.php")
.then((r) => {
return r.json();
})
.then((j) => {
return j.projects;
})
.catch((e) => {
console.log(e);
return {};
2020-11-08 15:21:51 +01:00
});
},
startRecord(projectId, startTime = new Date()) {
return request("/startRecord.php", {
project_id: projectId,
start_time: dateToString(startTime),
})
.then((r) => {
return r.json();
})
.then((j) => {
return addDuration(j.records[0]);
})
.catch((e) => {
console.log(e);
return undefined;
});
},
getRecord(recordId) {
return request("/getRecord.php", {
record_id: recordId,
})
.then((r) => {
return r.json();
})
.then((j) => {
return addDuration(j.records[0]);
})
.catch((e) => {
console.log(e);
return undefined;
});
},
getRunningRecords() {
return request("/getRunningRecords.php")
.then((r) => {
return r.json();
})
.then((j) => {
var records = Object.values(j.records);
records.forEach((r) => {
r = addDuration(r);
});
return records;
})
.catch((e) => {
console.log(e);
return undefined;
});
},
endRecord(recordId, endTime = new Date()) {
return request("/endRecord.php", {
record_id: recordId,
end_time: dateToString(endTime),
}).catch((e) => {
console.log(e);
return undefined;
});
},
2020-11-08 15:21:51 +01:00
};
function request(path, json = {}, options = {}) {
json.api_key = getApiKey();
json.user_id = getUserId();
options.method = "POST";
options.body = JSON.stringify(json);
options.headers = {
"Content-Type": "application/json",
};
var url = API_URL + path;
return fetch(url, options);
}
function addDuration(record) {
if (record.end_time != null) return record;
record.duration =
(new Date().getTime() - new Date(record.start_time).getTime()) / 1000;
return record;
}
function dateToString(date) {
return (
date.getFullYear() +
"-" +
(date.getMonth() + 1) +
"-" +
date.getDate() +
" " +
date.getHours() +
":" +
date.getMinutes() +
":" +
date.getSeconds()
);
}