@zburn/core
Version:
Core utilities for the ZBURN ecosystem.
68 lines (61 loc) • 2.28 kB
JavaScript
const https = require('https');
const { loadConfig } = require('../../config')
const config = loadConfig();
const httpsAgent = new https.Agent({
rejectUnauthorized: false
});
async function stimuleCidOnPublicGateways(cid) {
for (const gateway of config.stimulate_gateways) {
const url = gateway + cid;
try {
const res = await fetch(url, { method: 'HEAD', timeout: 5000 });
if (res.ok) {
console.log(`STIMULATION SUCCESS: Gateway ${gateway} responded OK for CID ${cid}`);
} else {
console.warn(`STIMULATION WARNING: Gateway ${gateway} responded ${res.status} for CID ${cid}`);
}
} catch (err) {
console.error(`STIMULATION ERROR: Error contacting gateway ${gateway} for CID ${cid}:`, err.message);
}
}
}
function interpolate(template, cid) {
if (typeof template === 'string') {
return template.replace(/{{cid}}/g, cid);
}
const str = JSON.stringify(template).replace(/{{cid}}/g, cid);
return JSON.parse(str);
}
async function pinEveryWhere(cid) {
for (const svc of config.pin_gateways) {
const url = interpolate(svc.urlTemplate, cid);
const method = svc.method.toUpperCase();
const headers = { ...(svc.headers || {}) };
let body = null;
// Auth
if (svc.auth?.type === 'Bearer') {
const token = process.env[svc.auth.tokenEnvVar] ? process.env[svc.auth.tokenEnvVar] : config.pin_env_var[svc.auth.tokenEnvVar] ? config.pin_env_var[svc.auth.tokenEnvVar] : "";
headers['Authorization'] = `Bearer ${token}`;
}
// Body
if (svc.bodyTemplate && method === 'POST') {
body = JSON.stringify(interpolate(svc.bodyTemplate, cid));
headers['Content-Type'] = headers['Content-Type'] || 'application/json';
}
try {
const res = await fetch(url, { method, headers, body, agent: httpsAgent });
if (!res.ok) {
console.error(`PIN ERROR ${res.status} ${res.statusText} @ ${url}`);
continue;
}
const result = await res.json().catch(() => null);
console.log(`PIN SUCCESS @ ${url}`, result);
} catch (err) {
console.error(`PIN EXCEPTION @ ${url}`, err);
}
}
}
module.exports = {
stimuleCidOnPublicGateways,
pinEveryWhere
};