-
Notifications
You must be signed in to change notification settings - Fork 5.6k
Expand file tree
/
Copy pathaxios.ts
More file actions
204 lines (179 loc) · 5.53 KB
/
axios.ts
File metadata and controls
204 lines (179 loc) · 5.53 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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
import axios, { AxiosHeaders } from "axios";
import { AxiosRequestConfig } from "./index";
import * as querystring from "querystring";
import { cloneSafe } from "./utils";
import { ConfigurationError } from "./errors";
function cleanObject(o = {}) {
for (const k in o) {
if (typeof o[k] === "undefined") {
delete o[k];
}
}
}
// remove query params from url and put into config.params
function removeSearchFromUrl(config: AxiosRequestConfig) {
if (!config.url) return;
const {
url, baseURL,
} = config;
const newUrl = new URL((baseURL ?? "") + url);
const queryString = newUrl.search.substr(1);
if (queryString) {
// https://stackoverflow.com/a/8649003/387413
const urlParams = JSON.parse("{\"" + queryString.replace(/&/g, "\",\"").replace(/=/g, "\":\"") + "\"}", function (key, value) {
return key === ""
? value
: decodeURIComponent(value);
});
for (const k in urlParams) {
if (!config.params) config.params = {};
if (k in config.params) continue; // params object > url query params
config.params[k] = urlParams[k];
}
newUrl.search = "";
config.url = newUrl.toString(); // if ends with ? should be okay, but could be cleaner
}
}
// https://github.com/ttezel/twit/blob/master/lib/helpers.js#L11
function oauth1ParamsSerializer(p: any) {
return querystring.stringify(p)
.replace(/!/g, "%21")
.replace(/'/g, "%27")
.replace(/\(/g, "%28")
.replace(/\)/g, "%29")
.replace(/\*/g, "%2A");
}
export function transformConfigForOauth(config: AxiosRequestConfig) {
const newUrl = axios.getUri({
...config,
paramsSerializer: oauth1ParamsSerializer,
});
const requestData = {
method: config.method || "get",
url: newUrl,
};
// the OAuth specification explicitly states that only form-encoded data should be included
let hasContentType = false;
let formEncodedContentType = false;
for (const k in config.headers || {}) {
if (/content-type/i.test(k)) {
hasContentType = true;
formEncodedContentType = config.headers?.[k] === "application/x-www-form-urlencoded";
break;
}
}
if (config.data && typeof config.data === "object" && formEncodedContentType) {
(requestData as any).data = config.data;
} else if (typeof config.data === "string" && (!hasContentType || formEncodedContentType)) {
(requestData as any).data = querystring.parse(config.data);
}
config.paramsSerializer = oauth1ParamsSerializer;
return requestData;
}
async function getOauthSignature(config: AxiosRequestConfig, signConfig: any) {
const {
oauthSignerUri, token,
} = signConfig;
const requestData = transformConfigForOauth(config);
const payload = {
requestData,
token,
};
return (await axios.post(oauthSignerUri, payload)).data;
}
// XXX warn about mutating config object... or clone?
async function callAxios(step: any, config: AxiosRequestConfig, signConfig?: any) {
cleanObject(config.headers);
cleanObject(config.params);
if (typeof config.data === "object") {
cleanObject(config.data);
}
if (config.body != null) {
throw new ConfigurationError("unexpected body, use only data instead");
}
removeSearchFromUrl(config);
// OAuth1 request
if (signConfig) {
const oauthSignature = await getOauthSignature(config, signConfig);
if (!config.headers) config.headers = {};
config.headers.Authorization = oauthSignature;
}
try {
if (config.debug) {
stepExport(step, config, "debug_config");
}
const response = await axios(config);
if (config.debug) {
stepExport(step, response.data, "debug_response");
}
return config.returnFullResponse
? response
: response.data;
} catch (err) {
if (err.response) {
convertAxiosError(err);
stepExport(step, err.response, "debug");
}
throw err;
}
}
function stepExport(step: any, message: any, key: string) {
message = cloneSafe(message);
if (step) {
if (step.export) {
step.export(key, message);
return;
}
step[key] = message;
}
console.log(`export: ${key} - ${JSON.stringify(message, null, 2)}`);
}
function convertAxiosError(err) {
delete err.response.request;
err.name = `${err.name} - ${err.message}`;
try {
err.message = JSON.stringify(err.response.data);
}
catch (error) {
console.error("Error trying to convert `err.response.data` to string");
}
return err;
}
function create(config?: AxiosRequestConfig, signConfig?: any) {
const axiosInstance = axios.create(config);
if (config?.debug) {
stepExport(this, config, "debug_config");
}
axiosInstance.interceptors.request.use(async (config) => {
if (signConfig) {
const oauthSignature = await getOauthSignature(config, signConfig);
if (!config.headers) config.headers = new AxiosHeaders();
config.headers.Authorization = oauthSignature;
}
cleanObject(config.headers);
cleanObject(config.params);
if (typeof config.data === "object") {
cleanObject(config.data);
}
removeSearchFromUrl(config);
return config;
});
axiosInstance.interceptors.response.use((response) => {
const config: AxiosRequestConfig = response.config;
if (config.debug) {
stepExport(this, response.data, "debug_response");
}
return config.returnFullResponse
? response
: response.data;
}, (error) => {
if (error.response) {
convertAxiosError(error);
stepExport(this, error.response, "debug");
}
throw error;
});
return axiosInstance;
}
callAxios.create = create;
export default callAxios;