reveil/ui/src/lib/alarmsingle.js

97 lines
2.4 KiB
JavaScript
Raw Normal View History

2022-10-05 20:33:31 +00:00
export class AlarmSingle {
constructor(res) {
if (res) {
this.update(res);
}
}
update({ id, time, routines, comment }) {
this.id = id;
this.time = new Date(time);
2022-12-15 15:29:48 +00:00
this.routines = routines == null ? [] : routines;
2022-10-05 20:33:31 +00:00
this.comment = comment;
2022-12-15 15:29:48 +00:00
if (this.routines.length < 1) {
this.routines.push("");
}
2022-10-05 20:33:31 +00:00
}
async delete() {
const res = await fetch(`api/alarms/single/${this.id}`, {
method: 'DELETE',
headers: {'Accept': 'application/json'}
});
if (res.status == 200) {
return true;
} else {
throw new Error((await res.json()).errmsg);
}
}
async save() {
const res = await fetch(this.id?`api/alarms/single/${this.id}`:'api/alarms/single', {
method: this.id?'PUT':'POST',
headers: {'Accept': 'application/json'},
body: JSON.stringify(this),
});
if (res.status == 200) {
const data = await res.json();
this.update(data);
return data;
} else {
throw new Error((await res.json()).errmsg);
}
}
}
export async function getAlarmsSingle() {
const res = await fetch(`api/alarms/single`, {headers: {'Accept': 'application/json'}})
if (res.status == 200) {
const data = await res.json();
if (data === null)
return [];
else
return data.map((t) => new AlarmSingle(t));
} else {
throw new Error((await res.json()).errmsg);
}
}
export async function getAlarmSingle(aid) {
const res = await fetch(`api/alarms/single/${aid}`, {headers: {'Accept': 'application/json'}})
if (res.status == 200) {
return new AlarmSingle(await res.json());
} else {
throw new Error((await res.json()).errmsg);
}
}
2022-10-06 12:02:56 +00:00
export async function getNextAlarm() {
const res = await fetch(`api/alarms/next`, {headers: {'Accept': 'application/json'}})
if (res.status == 200) {
2022-10-15 12:34:55 +00:00
const data = await res.json();
if (data)
return new Date(data);
else
return data;
2022-10-06 12:02:56 +00:00
} else {
throw new Error((await res.json()).errmsg);
}
}
export async function newNCyclesAlarm(nCycles) {
const res = await fetch('api/alarms/single', {
method: 'POST',
headers: {'Accept': 'application/json'},
body: JSON.stringify({
time: new Date(Date.now() + 600000 + 5400000 * nCycles)
}),
});
if (res.status == 200) {
const data = await res.json();
return new AlarmSingle(data);
} else {
throw new Error((await res.json()).errmsg);
}
}