This repository has been archived by the owner on Sep 8, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
110 lines (93 loc) · 2.61 KB
/
index.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
/*
This api client uses fetch.
Assumes all responses are json.
*/
const { isArray, isPlainObject, isString, merge } = require('lodash');
const defaultBaseUrl = "https://littlesis.org";
function validateResponse(res) {
if (res.status >= 200 && res.status < 300) { return res; }
throw `response failed with status code: ${res.status}`;
};
function transformPostData(data) {
if (isString(data)) {
return data;
} else if (isPlainObject(data)) {
return JSON.stringify(data);
} else {
throw "Post must be a plain object or a string";
}
}
function getCsrfToken() {
return document.head
.querySelector('meta[name="csrf-token"]')
.content;
}
function postHeaders() {
return {
'Content-Type': "application/json",
'Accept': "application/json",
'X-CSRF-Token': getCsrfToken()
};
}
/**
* Converts object to query parameter string for HTTP get requests
* Handles submission of one-dimensional arrays
*/
export function qs(queryParams) {
if (isString(queryParams) && queryParams.includes('=')) {
return `?${queryParams}`;
}
if (isPlainObject(queryParams)) {
let urlSearchParams = new URLSearchParams();
for (var key in queryParams) {
let val = queryParams[key];
if (isArray(val)) {
let arrayKey = key + "[]";
val.forEach(v => urlSearchParams.append(arrayKey, v));
} else {
urlSearchParams.set(key, val);
}
}
return '?' + urlSearchParams.toString();
}
return '';
};
const getFetchOptions = {
'method': "GET",
'credentials': "same-origin",
'headers': { "Accept": "application/json" }
};
// get() and post() take the full url as the first parameter.
export function get(url, params) {
return fetch(url + qs(params), getFetchOptions)
.then(validateResponse)
.then(response => response.json());
}
export function post(url, data) {
return fetch(url, {
"method": "POST",
"credentials": 'same-origin',
"headers": postHeaders(),
"body": transformPostData(data)
})
.then(validateResponse)
.then(response => response.json());
}
// Creates an object with versions get() and post() that accept
// a relative path (i.e. /api/entities/123) using/ the `baseUrl`
//
// client("https://example.com").get("/foo/bar")
// is equivalent to get("https://example.com/foo/bar")
//
// baseUrl defaults to LittleSis.org
export function client(baseUrl) {
const toUrl = path => {
let url = new URL(baseUrl || defaultBaseUrl);
url.pathname = path;
return url.toString();
};
return {
"get": (path, params) => get(toUrl(path), params),
"post": (path, data) => post(toUrl(path), data)
};
}