release: Mark VIII 1.0
This commit is contained in:
@@ -0,0 +1,42 @@
|
||||
'use strict';
|
||||
|
||||
const PagerAPI = (() => {
|
||||
let apiBase = '';
|
||||
let on401 = null;
|
||||
async function request(method, path, body) {
|
||||
const opts = { method, headers: {}, credentials: 'include' };
|
||||
if (body !== undefined) {
|
||||
opts.headers['Content-Type'] = 'application/json';
|
||||
opts.body = JSON.stringify(body);
|
||||
}
|
||||
const res = await fetch(apiBase + path, opts);
|
||||
if (res.status === 401) {
|
||||
if (on401) on401();
|
||||
throw new Error('unauthorized');
|
||||
}
|
||||
const ct = res.headers.get('Content-Type') || '';
|
||||
let data;
|
||||
if (ct.indexOf('json') !== -1) {
|
||||
try { data = await res.json(); }
|
||||
catch (e) { data = null; }
|
||||
} else {
|
||||
data = await res.text();
|
||||
}
|
||||
if (!res.ok) {
|
||||
const message = data && data.error ? data.error : ('HTTP ' + res.status);
|
||||
const error = new Error(message);
|
||||
error.status = res.status;
|
||||
error.data = data;
|
||||
throw error;
|
||||
}
|
||||
return { status: res.status, data };
|
||||
}
|
||||
return {
|
||||
setBase: (b) => { apiBase = b; },
|
||||
on401: (fn) => { on401 = fn; },
|
||||
get: (p) => request('GET', p),
|
||||
post: (p, b) => request('POST', p, b === undefined ? {} : b),
|
||||
del: (p, b) => request('DELETE', p, b === undefined ? {} : b),
|
||||
login: async (username, password) => request('POST', '/api/login', { username, password })
|
||||
};
|
||||
})();
|
||||
Reference in New Issue
Block a user