File size: 1,835 Bytes
abf702c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import { auth } from './auth'

const BASE_URL = import.meta.env.PROD ? '/api' : 'http://localhost:8000/api'

export const api = {
    get: async (endpoint) => {
        const headers = {}
        if (auth.token.value) {
            headers['Authorization'] = `Bearer ${auth.token.value}`
        }
        const response = await fetch(`${BASE_URL}${endpoint}`, { headers })
        if (response.status === 401) auth.logout()
        return response.json()
    },

    post: async (endpoint, data) => {
        const headers = { 'Content-Type': 'application/json' }
        if (auth.token.value) {
            headers['Authorization'] = `Bearer ${auth.token.value}`
        }
        const response = await fetch(`${BASE_URL}${endpoint}`, {
            method: 'POST',
            headers,
            body: JSON.stringify(data)
        })
        if (response.status === 401) auth.logout()
        return response.json()
    },

    put: async (endpoint, data) => {
        const headers = { 'Content-Type': 'application/json' }
        if (auth.token.value) {
            headers['Authorization'] = `Bearer ${auth.token.value}`
        }
        const response = await fetch(`${BASE_URL}${endpoint}`, {
            method: 'PUT',
            headers,
            body: JSON.stringify(data)
        })
        if (response.status === 401) auth.logout()
        return response.json()
    },

    delete: async (endpoint) => {
        const headers = {}
        if (auth.token.value) {
            headers['Authorization'] = `Bearer ${auth.token.value}`
        }
        const response = await fetch(`${BASE_URL}${endpoint}`, {
            method: 'DELETE',
            headers
        })
        if (response.status === 401) auth.logout()
        return response.json()
    }
}