-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlib.js
115 lines (101 loc) · 2.71 KB
/
lib.js
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
import axios from 'axios'
class Auth {
constructor(api) {
this.api = api
}
login = async (email, password) => {
const formData = new FormData()
formData.append('username', email)
formData.append('password', password)
return await this.api.post('/auth/login', formData)
}
logout = async () => await this.api.post('/auth/logout', {})
}
class Me {
constructor(api) {
this.api = api
}
get = async () => await this.api.get('/users/me')
patch = async (data) => await this.api.patch('/users/me', data)
}
class User {
constructor(api) {
this.api = api
}
getList = async (Page = 0, PerPage = 10) =>
await this.api.get('/users', {
headers: { Page, PerPage },
})
get = async (id) => await this.api.get(`/users/${id}`)
patch = async (id, data) => await this.api.patch(`/users/${id}`, data)
delete = async (id) => await this.api.delete(`/users/${id}`)
}
export class API {
constructor(prefix = '/api/v0', config = {}) {
this.api = axios.create({
baseURL: prefix,
withCredentials: true,
...config,
})
this.auth = new Auth(this)
this.me = new Me(this)
this.user = new User(this)
}
get = async (...args) => {
try {
const response = await this.api.get(...args)
return { ...response.data, ok: true }
} catch (error) {
return { ...error, ok: false }
}
}
patch = async (...args) => {
try {
const response = await this.api.patch(...args)
return { ...response.data, ok: true }
} catch (error) {
return { ...error, ok: false }
}
}
post = async (...args) => {
try {
const response = await this.api.post(...args)
return { ...response.data, ok: true }
} catch (error) {
return { ...error, ok: false }
}
}
delete = async (...args) => {
try {
const response = await this.api.delete(...args)
return { ...response.data, ok: true }
} catch (error) {
return { ...error, ok: false }
}
}
errors = (response) => {
const res = response.response
const data = res && res.data && typeof res.data !== 'string' ? res.data : {}
if (!data.message) {
if (data.msg) {
data.message = data.msg
} else if (data.statusText) {
data.message = data.statusText
} else if (data.status) {
data.message = data.status
} else if (res.statusText) {
data.message = res.statusText
} else if (res.status) {
data.message = res.status
}
}
if (data.errors) {
Object.getOwnPropertyNames(data.errors).forEach((property) => {
if (property !== 'message') {
data.errors[property] = data.errors[property].join(' ')
}
})
}
return data
}
}