reveil/ui/src/lib/routine.js

62 lines
1.5 KiB
JavaScript

export class Routine {
constructor(res) {
if (res) {
this.update(res);
}
}
update({ id, name, path, steps }) {
this.id = id;
this.name = name;
this.path = path;
steps.sort((a, b) => a.delay - b.delay);
this.steps = steps;
}
async delete() {
const res = await fetch(`api/routines/${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/routines/${this.id}`:'api/routines', {
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 getRoutines() {
const res = await fetch(`api/routines`, {headers: {'Accept': 'application/json'}})
if (res.status == 200) {
return (await res.json()).map((r) => new Routine(r));
} else {
throw new Error((await res.json()).errmsg);
}
}
export async function getRoutine(rid) {
const res = await fetch(`api/routines/${rid}`, {headers: {'Accept': 'application/json'}})
if (res.status == 200) {
return new Routine(await res.json());
} else {
throw new Error((await res.json()).errmsg);
}
}