This repository has been archived on 2024-03-28. You can view files and clone it, but cannot push or open issues or pull requests.
atsebay.t/ui/src/lib/key.js

74 lines
1.8 KiB
JavaScript

export class Key {
constructor(res) {
if (res) {
this.update(res);
}
}
update({ id, id_user, type, key, time, infos }) {
this.id = id;
this.id_user = id_user;
this.type = type;
this.key = key;
this.time = time;
this.infos = infos;
}
async delete() {
const res = await fetch(`api/keys/${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/keys/${this.id}`:'api/keys', {
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 getKeys(userid) {
const res = await fetch(userid?`api/users/${userid}/keys`:`api/keys`, {headers: {'Accept': 'application/json'}})
if (res.status == 200) {
return await res.json();
} else {
throw new Error((await res.json()).errmsg);
}
}
export async function getKey(kid, userid) {
const res = await fetch(userid?`api/users/${userid}/keys/${kid}`:`api/keys/${kid}`, {headers: {'Accept': 'application/json'}})
if (res.status == 200) {
return new Key(await res.json());
} else {
throw new Error((await res.json()).errmsg);
}
}
export async function deleteKey(kid, userid) {
const res = await fetch(userid?`api/users/${userid}/keys/${kid}`:`api/keys/${kid}`, {
method: 'DELETE',
headers: {'Accept': 'application/json'}
})
if (res.status == 200) {
return await res.json();
} else {
throw new Error((await res.json()).errmsg);
}
}