-
Notifications
You must be signed in to change notification settings - Fork 2
/
fetch.js
54 lines (43 loc) · 1.28 KB
/
fetch.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
import { create } from "apisauce";
let api;
function createApiPromise(response) {
return new Promise((resolve, reject) => {
if (response.ok && response.data) {
resolve(response.data);
} else {
reject(response.data || response.problem || "SOMETHING WENT WRONG");
}
});
}
function encodeParams(params) {
return Object.entries(params)
.map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
.join('&');
}
export function createApi(baseURL) {
api = create({
baseURL,
headers: {
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
},
});
}
export async function get(url, params) {
if (!api) throw new Error('API not initialized. Call createApi first.');
const body = encodeParams(params);
const response = await api.post(url, body);
if (__DEV__) {
console.log("Piano SDK - get - response:", response);
}
return createApiPromise(response);
}
export async function post(url, params, body) {
if (!api) throw new Error('API not initialized. Call createApi first.');
const queryString = encodeParams(params);
const response = await api.post(`${url}?${queryString}`, body, {
headers: {
"Content-Type": "application/json",
},
});
return createApiPromise(response);
}