-
Notifications
You must be signed in to change notification settings - Fork 66
/
NodeApi.js
201 lines (175 loc) · 6.63 KB
/
NodeApi.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
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
import axios from 'axios';
import * as rax from 'retry-axios';
import json from 'json-bigint';
import DateTime from '../DateTime';
import Strings from '../Strings';
const TRANSACTIONS_BY_ADDRESS_LIMIT = 100;
const ASSETS_PER_PAGE = 100;
const parseResponse = (response) => {
if (typeof response === 'string') {
try {
return json.parse(response);
} catch (e) {
// ignore
}
}
return response;
};
const DEFAULT_AXIOS_CONFIG = {
transformResponse: [parseResponse],
};
const CUSTOM_AXIOS_CONFIG = {
withCredentials: true,
headers: {
common: {
['Cache-Control']: 'no-cache'
}
}
};
const buildAxiosConfig = useCustomRequestConfig => {
let result = DEFAULT_AXIOS_CONFIG;
if (useCustomRequestConfig)
result = Object.assign({}, result, CUSTOM_AXIOS_CONFIG);
return result;
};
const buildRetryableAxiosConfig = axiosInstance => ({
instance: axiosInstance,
retryDelay: 100,
retry: 5,
httpMethodsToRetry: ['GET'],
shouldRetry: shouldRetryRequest
});
export const replaceTimestampWithDateTime = obj => {
if (obj.timestamp) {
obj.timestamp = new DateTime(obj.timestamp);
}
return obj;
};
const transformTimestampToDateTime = (responseData) => {
if (Array.isArray(responseData)) {
responseData.forEach(replaceTimestampWithDateTime);
} else {
replaceTimestampWithDateTime(responseData);
}
return responseData;
};
/**
* Determine based on config if we should retry the request.
* @param err The AxiosError passed to the interceptor.
*/
function shouldRetryRequest(err) {
const config = err.config.raxConfig;
// If there's no config, or retries are disabled, return.
if (!config || config.retry === 0) {
return false;
}
config.currentRetryAttempt = config.currentRetryAttempt || 0;
// Check if this error has no response (ETIMEDOUT, ENOTFOUND, etc)
if (!err.response && (config.currentRetryAttempt >= config.noResponseRetries)) {
return false;
}
// Only retry with configured HttpMethods.
const methodsToRetry = Array.isArray(config.httpMethodsToRetry) ?
config.httpMethodsToRetry :
Object.values(config.httpMethodsToRetry);
if (!err.config.method ||
methodsToRetry.indexOf(err.config.method.toUpperCase()) < 0) {
return false;
}
// If this wasn't in the list of status codes where we want
// to automatically retry, return.
if (err.response && err.response.status) {
let isInRange = false;
for (const [min, max] of config.statusCodesToRetry) {
const status = err.response.status;
if (status >= min && status <= max) {
isInRange = true;
break;
}
}
if (!isInRange) {
return false;
}
}
// If we are out of retry attempts, return
if (config.currentRetryAttempt >= config.retry) {
return false;
}
return true;
}
export const nodeApi = (baseUrl, useCustomRequestConfig) => {
const trimmedUrl = Strings.trimEnd(baseUrl, '/');
const config = buildAxiosConfig(useCustomRequestConfig);
const nodeAxios = axios.create(config);
const get = (url, config) => nodeAxios.get(trimmedUrl + url, config);
const retryableAxios = axios.create(config);
retryableAxios.defaults.raxConfig = buildRetryableAxiosConfig(retryableAxios);
rax.attach(retryableAxios);
const retryableGet = (url, config) => retryableAxios.get(trimmedUrl + url, config);
return {
version: () => get('/node/version'),
baseTarget: () => get('/consensus/basetarget'),
addresses: {
details: (address) => retryableGet(`/addresses/balance/details/${address}`),
aliases: (address) => retryableGet(`/alias/by-address/${address}`),
validate: (address) => retryableGet(`/addresses/validate/${address}`),
data: (address) => retryableGet(`/addresses/data/${address}`),
script: (address) => retryableGet(`/addresses/scriptInfo/${address}`)
},
blocks: {
height: () => get('/blocks/height'),
heightBySignature: (signature) => get(`/blocks/height/${signature}`),
delay: (fromSignature, count) => get(`/blocks/delay/${fromSignature}/${count}`),
at: (height) => retryableGet(`/blocks/at/${height}`, {
transformResponse: axios.defaults.transformResponse.concat(transformTimestampToDateTime)
}),
headers: {
last: () => retryableGet('/blocks/headers/last', {
transformResponse: axios.defaults.transformResponse.concat(transformTimestampToDateTime)
}),
at: (height) => retryableGet(`/blocks/headers/at/${height}`, {
transformResponse: axios.defaults.transformResponse.concat(transformTimestampToDateTime)
}),
sequence: (from, to) => retryableGet(`/blocks/headers/seq/${from}/${to}`, {
transformResponse: axios.defaults.transformResponse.concat(transformTimestampToDateTime)
})
}
},
transactions: {
unconfirmed: () => retryableGet('/transactions/unconfirmed'),
utxSize: () => retryableGet('/transactions/unconfirmed/size'),
info: id => retryableGet(`/transactions/info/${id}`),
address: (address, limit, after) => {
const top = limit || TRANSACTIONS_BY_ADDRESS_LIMIT;
const config = after ? {
params: {
after
}
} : undefined;
return retryableGet(`/transactions/address/${address}/limit/${top}`, config);
},
stateChanges: id => retryableGet(`/debug/stateChanges/info/${id}`)
},
aliases: {
address: (alias) => retryableGet(`/alias/by-alias/${alias}`)
},
assets: {
balance: (address) => retryableGet(`/assets/balance/${address}`),
details: (assetId, full) => retryableGet(`/assets/details/${assetId}`, {
params: {
full: !!full
}
}),
nft: (address, limit, after) => {
const top = limit || ASSETS_PER_PAGE;
const config = after ? {
params: {
after
}
} : undefined;
return retryableGet(`/assets/nft/${address}/limit/${top}`, config);
}
},
peers: () => retryableGet('/peers/connected'),
};
};