goly-chrome/goly.js
jolheiser 1b640d2c1a
Better errors and status checking
Signed-off-by: jolheiser <john.olheiser@gmail.com>
2020-07-10 22:11:07 -05:00

67 lines
2.0 KiB
JavaScript

class Link {
constructor(short, url, uses, expiry, last_used) {
this.short = short;
this.url = url;
this.uses = uses;
this.expiry = expiry;
this.last_used = last_used;
}
}
class Status {
constructor(count, version) {
this.count = count;
this.version = version;
}
}
class Client {
constructor(baseURL) {
this.baseURL = baseURL;
}
async getStatus() {
if (this.baseURL === '') throw 'Goly base URL cannot be blank.\nConfigure a valid Goly base URL.';
const resp = await fetch(`${this.baseURL}/api/status`).catch((err) => {
throw `Couldn't connect to ${this.baseURL}`;
});
const json = await resp.json();
if (!resp.ok) {
throw JSON.stringify(json);
}
return Object.assign(new Status(), json);
}
async getLink(short) {
if (this.baseURL === '') throw 'Goly base URL cannot be blank.\nConfigure a valid Goly base URL.';
const resp = await fetch(`${this.baseURL}/api/link/${short}`);
const json = await resp.json();
if (json.status !== 200) {
throw JSON.stringify(json);
}
return Object.assign(new Link(), json.link);
}
async getQR(short) {
if (this.baseURL === '') throw 'Goly base URL cannot be blank. Configure a valid Goly base URL.';
const resp = await fetch(`${this.baseURL}/api/link/${short}/qr`);
if (!resp.ok) {
throw JSON.stringify(await resp.json());
}
return await resp.blob();
}
async setLink(link) {
if (this.baseURL === '') throw 'Goly base URL cannot be blank.\nConfigure a valid Goly base URL.';
const resp = await fetch(`${this.baseURL}/api/link`, {
method: 'POST',
body: JSON.stringify(link),
});
const json = await resp.json();
if (json.status !== 201) {
throw JSON.stringify(json);
}
return Object.assign(new Link(), json.link);
}
}