secutorpro commited on
Commit
f828f2d
·
verified ·
1 Parent(s): d07a6aa

fetch client with JWT session

Browse files
Files changed (1) hide show
  1. web/src/api.js +33 -0
web/src/api.js ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ let token = sessionStorage.getItem('dc_token') || '';
2
+
3
+ export function setToken(t) {
4
+ token = t || '';
5
+ if (token) sessionStorage.setItem('dc_token', token);
6
+ else sessionStorage.removeItem('dc_token');
7
+ }
8
+
9
+ export function getToken() { return token; }
10
+
11
+ async function request(path, options = {}) {
12
+ const res = await fetch(`/api${path}`, {
13
+ ...options,
14
+ headers: {
15
+ 'Content-Type': 'application/json',
16
+ ...(token ? { Authorization: `Bearer ${token}` } : {}),
17
+ },
18
+ });
19
+ if (res.status === 401) {
20
+ setToken('');
21
+ throw new Error('Session expired — log in again');
22
+ }
23
+ const data = await res.json().catch(() => null);
24
+ if (!res.ok) throw new Error(data?.error || res.statusText);
25
+ return data;
26
+ }
27
+
28
+ export const api = {
29
+ get: (p) => request(p),
30
+ post: (p, body) => request(p, { method: 'POST', body: JSON.stringify(body ?? {}) }),
31
+ put: (p, body) => request(p, { method: 'PUT', body: JSON.stringify(body ?? {}) }),
32
+ del: (p) => request(p, { method: 'DELETE' }),
33
+ };