Improve sip API error handling

This commit is contained in:
Mononaut 2023-08-25 16:40:03 +09:00
parent 8bc1eaebc0
commit 6852319e4d
No known key found for this signature in database
GPG key ID: A3F058E41374C04E
3 changed files with 33 additions and 9 deletions

View file

@ -1,5 +1,17 @@
import fetch from 'node-fetch-commonjs';
import config from './config';
import http from 'node:http';
import https from 'node:https';
const httpAgent = new http.Agent({ keepAlive: true });
const httpsAgent = new https.Agent({ keepAlive: true });
const agentSelector = function(_parsedURL: any) {
if (_parsedURL.protocol == 'http:') {
return httpAgent;
} else {
return httpsAgent;
}
}
interface Match {
render: boolean;
@ -16,6 +28,15 @@ interface SipTemplate {
getData: Function;
}
async function sipFetchJSON(url, defaultVal = null) {
try {
const response = await fetch(url, { agent: agentSelector });
return response.ok ? response.json() : defaultVal;
} catch (error) {
return defaultVal;
}
}
const routes = {
about: {
title: "About",
@ -41,11 +62,11 @@ const routes = {
if (params?.length) {
let blockId = params[0];
if (blockId.length !== 64) {
blockId = await (await fetch(config.API.ESPLORA + `/block-height/${blockId}`)).text();
blockId = await (await fetch(config.API.ESPLORA + `/block-height/${blockId}`, { agent: agentSelector })).text();
}
const [block, transactions] = await Promise.all([
(await fetch(config.API.MEMPOOL + `/block/${blockId}`)).json(),
(await fetch(config.API.ESPLORA + `/block/${blockId}/txids`)).json()
sipFetchJSON(config.API.MEMPOOL + `/block/${blockId}`),
sipFetchJSON(config.API.ESPLORA + `/block/${blockId}/txids`),
])
return {
block,

View file

@ -79,12 +79,14 @@
<td><%= data.block.merkle_root %></td>
</tr>
</table>
<h2><%= data.transactions.length %> Transactions</h2>
<ol>
<% data.transactions.forEach((txid, i) => { %>
<li><a href="/tx/<%= txid %>"><%= txid %></a><% if (i === 0) { %> (Coinbase)<% } %></li>
<% }); %>
</ol>
<% if (data.transactions) { %>
<h2><%= data.transactions.length %> Transactions</h2>
<ol>
<% data.transactions.forEach((txid, i) => { %>
<li><a href="/tx/<%= txid %>"><%= txid %></a><% if (i === 0) { %> (Coinbase)<% } %></li>
<% }); %>
</ol>
<% } %>
</div>
<%- include('footer'); %>
</body>

View file

@ -1,3 +1,4 @@
<br><hr><br>
<app-global-footer>
<footer>
<div class="container-fluid">