-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathapi.js
79 lines (64 loc) · 1.55 KB
/
api.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
import axios from 'axios';
class APICollection {
constructor(params = {}) {
console.log(params);
this._name = params.name || null;
this._api = params.api || null;
}
get axios() {
return this._api._axios;
}
async list(params = {}) {
let resp = await this.axios.get(this._name, { params: params });
return resp.data;
}
post(data = {}, params = {}) {
return this.add(data, params);
}
async add(data = {}, params = {}) {
let resp = await this.axios.post(this._name, data, {params: params});
return resp.data;
}
async edit(data = {}, params = {}) {
let id = data.id || data._id || null;
if (!id) {
throw 'id or _id is required';
}
let resp = await this.axios.put(this._name+'/'+id, data, {params: params});
return resp.data;
}
async delete(data = {}) {
let id = data.id || data._id || null;
if (!id) {
throw 'id or _id is required';
}
let resp = await this.axios.delete(this._name+'/'+id);
if (resp && resp.data && resp.data.success) {
return true;
} else {
return false;
}
}
}
class API {
constructor(params = {}) {
this._baseDomain = params.baseDomain || document.location.origin || null;
this._basePath = params.basePath || (''+this._baseDomain+'/api');
this._collections = {};
this._axios = axios.create({
baseURL: this._basePath
});
}
getCollection(name) {
if (this._collections[name]) {
return this._collections[name];
} else {
this._collections[name] = new APICollection({
name: name,
api: this
});
return this._collections[name];
}
}
}
export default API;