-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathtatum.connector.ts
223 lines (196 loc) Β· 6.54 KB
/
tatum.connector.ts
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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
import { Container, Service } from 'typedi'
import { JsonRpcCall } from '../dto'
import { ApiVersion } from '../service'
import { CONFIG, Constant, EnvUtils, Utils } from '../util'
import { DefaultBodyType, DefaultParamsType, FileUploadRequest, GetUrl, SdkRequest } from './connector.dto'
@Service({
factory: (data: { id: string }) => {
return new TatumConnector(data.id)
},
transient: true,
})
export class TatumConnector {
constructor(private readonly id: string) {}
public async get<RESPONSE, PARAMS extends DefaultParamsType = DefaultParamsType>(request: GetUrl<PARAMS>) {
return this.request<RESPONSE, PARAMS>({ ...request, method: 'GET' }) as Promise<RESPONSE>
}
public async rpcCall<RESPONSE>(url: string, body: JsonRpcCall | JsonRpcCall[]) {
return this.request<RESPONSE>({ body, method: 'POST' }, 0, url) as Promise<RESPONSE>
}
public async post<RESPONSE, BODY extends DefaultBodyType = DefaultBodyType>(
request: SdkRequest<DefaultParamsType, BODY>,
) {
return this.request<RESPONSE, DefaultParamsType, BODY>({
...request,
method: 'POST',
}) as Promise<RESPONSE>
}
public async put<RESPONSE, BODY extends DefaultBodyType = DefaultBodyType>(
request: SdkRequest<DefaultParamsType, BODY>,
) {
return this.request<RESPONSE, DefaultParamsType, BODY>({
...request,
method: 'PUT',
}) as Promise<RESPONSE>
}
public async delete<RESPONSE>(request: GetUrl) {
return this.request<RESPONSE>({ ...request, method: 'DELETE' }) as Promise<RESPONSE>
}
public async uploadFile<RESPONSE>(request: FileUploadRequest) {
const formData = new FormData()
formData.append('file', new Blob([request.body]))
return this.request<RESPONSE>({ ...request, method: 'POST', body: formData }, 0) as Promise<RESPONSE>
}
public async getFile<RESPONSE, PARAMS extends DefaultParamsType = DefaultParamsType>(
request: GetUrl<PARAMS>,
) {
return this.request<RESPONSE, PARAMS>({ ...request, method: 'GET', isDownload: true }) as Promise<Blob>
}
private async request<
RESPONSE,
PARAMS extends DefaultParamsType = DefaultParamsType,
BODY extends DefaultBodyType = DefaultBodyType,
>(
{ path, params, body, method, basePath, isDownload }: SdkRequest<PARAMS, BODY>,
retry = 0,
externalUrl?: string,
): Promise<RESPONSE | Blob | undefined> {
const url = externalUrl || this.getUrl({ path, params, basePath })
const isUpload = body && body instanceof FormData
const headers = isUpload ? Utils.getBasicHeaders(this.id) : Utils.getHeaders(this.id)
let requestBody: string | FormData | null = null
if (isUpload) {
requestBody = body
} else if (body) {
requestBody = JSON.stringify(body)
}
const request: RequestInit = {
headers: headers,
method,
body: requestBody,
}
const start = Date.now()
try {
const res = await fetch(url, request)
const end = Date.now() - start
const responseBody = isDownload ? `Binary data` : await res.clone().text()
// Structure your log entry here
Utils.log({
id: this.id,
message: `[${request.method}] ${url} -> ${res.status} (${end}ms)`,
data: {
request: {
method: request.method,
url: url,
body: request.body,
},
response: {
status: res.status,
time: `${end}ms`,
body: responseBody,
},
headers: Utils.headersToJson(headers),
},
})
if (res.ok) {
if (!responseBody) {
return undefined
}
if (isDownload) {
return await res.blob()
}
const response = await res.json()
if (response?.error) {
return response
}
return response
}
// Retry only in case of 5xx error
if (res.status >= 500 && res.status < 600) {
return await this.retry(url, request, responseBody, retry)
}
throw responseBody
} catch (error) {
const end = Date.now() - start
Utils.log({
id: this.id,
message: `[${request.method}] ${url} -> (${end}ms)`,
data: {
request: {
method: request.method,
url: url,
body: request.body,
},
error: JSON.stringify(error, Object.getOwnPropertyNames(error)),
time: `${end}ms`,
headers: Utils.headersToJson(headers),
},
})
return Promise.reject(error)
}
}
private getBaseUrl() {
const config = Container.of(this.id).get(CONFIG)
if (EnvUtils.isProcessAvailable() && process.env?.TATUM_URL) {
return process.env.TATUM_URL
}
return config.version === ApiVersion.V3 ? Constant.TATUM_API_URL.V3 : Constant.TATUM_API_URL.V4
}
private getUrl<PARAMS extends DefaultParamsType = DefaultParamsType>({
path,
params,
basePath,
}: GetUrl<PARAMS>) {
const config = Container.of(this.id).get(CONFIG)
const base = basePath || this.getBaseUrl()
const url = new URL(path && path?.length > 1 ? `${base}${path}` : base)
if (params) {
Object.keys(params)
.filter((key) => !!params[key])
.forEach((key) => url.searchParams.append(key, `${params[key]}`))
}
if (!Object.keys(config.apiKey || {})?.length && Constant.RPC.TESTNETS.includes(config.network)) {
url.searchParams.append('type', 'testnet')
}
return url.toString()
}
private async retry<RESPONSE>(
url: string,
request: RequestInit,
responseBody: string,
retry: number,
): Promise<RESPONSE | Blob | undefined> {
const { retryDelay, retryCount } = Container.of(this.id).get(CONFIG)
if (!retryCount) {
Utils.log({
id: this.id,
message: `Not retrying the request - no max retry count defined`,
data: { url, requestBody: request.body },
})
return Promise.reject(responseBody)
}
if (retry >= retryCount) {
Utils.log({
id: this.id,
message: `Not retrying the request for the '${retry}' time - exceeded max retry count ${retryCount}: `,
data: { url, requestBody: request.body },
})
return Promise.reject(responseBody)
}
retry++
await Utils.delay(retryDelay || 1000)
Utils.log({
id: this.id,
message: `Retrying the request for the '${retry}' time: `,
data: { url, requestBody: request.body },
})
return this.request(
{
method: request.method as string,
body: request.body ? JSON.parse(request.body as string) : null,
},
retry,
url,
)
}
}