-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathClient.js
114 lines (96 loc) · 3.48 KB
/
Client.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
// @flow
const API_BASE_PATH: string = "https://api.github.com";
export type FetchOptions = {
headers?: Object
};
function buildQueryString(params: Object): string {
return Object.keys(params)
.filter(v => v !== null)
.map(k => encodeURIComponent(k) + '=' + encodeURIComponent(params[k]))
.join('&');
}
function required(key: string) {
throw new Error(`Missing required parameter: ${key}`);
}
function makeClient() {
let before = [];
let after = [];
return {
before: (midlleware) => {
before.push(midlleware);
},
request: (url: string, params: Object, method: string = 'GET', options?: FetchOptions) => {
let requestOptions = Object.assign({}, options, { method: method });
if (before) {
before.forEach((middleware) => middleware(requestOptions));
}
return new Promise(
(resolve, reject) => {
if (method == 'POST' || method == 'PUT') {
requestOptions = Object.assign(
requestOptions,
{
body: JSON.stringify(params)
}
)
} else if (params && Object.keys(params).length > 0) { // Check that parameters exists
url += '?' + buildQueryString(params)
}
fetch(API_BASE_PATH + url, requestOptions).then(
(response) => {
if (response.status >= 200 && response.status < 300) {
resolve(response.json());
} else {
reject(response);
}
},
(err) => reject(err)
)
}
)
},
executeQL: async (query: string, variables: Object, options?: FetchOptions): Promise<any> => {
let requestOptions = Object.assign({}, options, { method: 'POST' });
if (before) {
before.forEach((middleware) => middleware(requestOptions));
}
requestOptions = Object.assign(
requestOptions,
{
body: JSON.stringify({
query: query.replace(/\n/g, ''),
variables: variables
})
}
);
try {
const response = await fetch(API_BASE_PATH + '/graphql', requestOptions);
if (response.status >= 200 && response.status < 300) {
const result = await response.json();
if (result.errors) {
return Promise.reject(result.errors);
}
if (result.data) {
return result.data;
}
} else {
return Promise.reject(response);
}
} catch (e) {
return Promise.reject(e)
}
return Promise.reject(new Error('Unknown GraphQL error'));
}
}
}
const defaultClient = makeClient();
const before = defaultClient.before;
const request = defaultClient.request;
const executeQL = defaultClient.executeQL;
export {
required,
makeClient,
before,
request,
executeQL
}