-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
139 lines (111 loc) · 3.65 KB
/
index.js
File metadata and controls
139 lines (111 loc) · 3.65 KB
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
// @flow
import { stringify } from 'qs';
import _ from 'lodash/fp';
import Environment from '../../constants/Environment';
import * as env from '../env';
import { apiRoutes } from '../../routes/api';
import createAjaxRequestTracker from './ajaxRequestTracker';
import ApiError from './ApiError';
type strictQuery = {|
page?: ?number,
|};
export let callApi;
const IS_BROWSER = !(window.callApi === undefined);
export function buildUrl(path: string, query: strictQuery) {
const filteredQuery = _.pickBy(_.identity, query);
return `${path}?${stringify(filteredQuery, { arrayFormat: 'brackets' })}`;
}
export function getCsrfToken() {
const isTest = env.get('RAILS_ENV') === Environment.TEST;
if (isTest) return null;
const metas = document.querySelectorAll('meta');
const token = _.find({ name: 'csrf-token' }, metas);
if (!token) throw new Error('Missing CSRF TOKEN in head');
return token.content;
}
export function parseRawParams(method: MethodType, rawParams: string | Object) {
return typeof rawParams === 'string' ? { method, url: rawParams } : Object.assign({}, { method }, rawParams);
}
export function buildReqUrl(params: Request) {
return params.url;
}
export function buildReqParams(params: Request) {
const reqParams = {};
reqParams.method = params.method;
if (params.data) {
reqParams.body = buildReqBody(params.data);
}
if (!params.remote) {
reqParams.credentials = 'same-origin';
if(IS_BROWSER) {
reqParams.headers = {
'Content-Type': 'application/json',
'X-CSRF-Token': apiUtils.getCsrfToken(),
};
} else {
reqParams.headers = {
'Content-Type': 'application/json',
};
}
} else if (params.remote && params.data && _.isPlainObject(parseImmutableData(params.data))) {
reqParams.headers = {
'Content-Type': 'application/json',
};
}
return reqParams;
}
function buildReqBody(data: any) {
const reqBody = parseImmutableData(data);
return _.isPlainObject(reqBody) ? JSON.stringify(reqBody) : reqBody;
}
function parseImmutableData(data: any) {
return typeof data.toJS === 'function' ? data.toJS() : data;
}
function checkResponseStatus(response: Response) {
if (response.ok) return response;
return response.json()
.then(errData => {
const isBadCsrfToken = response.status === 401 && errData.message === 'Bad Authenticity Token';
if (isBadCsrfToken && IS_BROWSER) window.location.reload();
const error = new ApiError(response.statusText, errData, response.status);
throw error;
});
}
function parseResponse(response: Response) {
return response.status !== 204 ? response.json() : response;
}
if(IS_BROWSER) {
callApi = function (method: MethodType, rawParams: string | Object) {
const parsedParams = parseRawParams(method, rawParams);
const reqUrl = buildReqUrl(parsedParams);
const reqParams = buildReqParams(parsedParams);
const ajaxRequestTracker = createAjaxRequestTracker();
ajaxRequestTracker.start();
return fetch(reqUrl, reqParams)
.then(res => {
ajaxRequestTracker.end();
return res;
})
.then(checkResponseStatus)
.then(parseResponse)
.catch(err => {
ajaxRequestTracker.end();
throw err;
});
}
} else {
callApi = function (method: MethodType, rawParams: string | Object) {
const parsedParams = parseRawParams(method, rawParams);
const reqUrl = buildReqUrl(parsedParams);
const reqParams = buildReqParams(parsedParams);
return fetch(reqUrl, reqParams)
.then(res => {
return res;
})
.then(checkResponseStatus)
.then(parseResponse)
.catch(err => {
throw err;
});
}
}