UNPKG

@logsn/arweave

Version:
63 lines (62 loc) 2.27 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const error_1 = require("./lib/error"); const ArweaveUtils = require("./lib/utils"); class Chunks { api; constructor(api) { this.api = api; } async getTransactionOffset(id) { const resp = await this.api.get(`tx/${id}/offset`); if (resp.status === 200) { return resp.data; } throw new Error(`Unable to get transaction offset: ${(0, error_1.getError)(resp)}`); } async getChunk(offset) { const resp = await this.api.get(`chunk/${offset}`); if (resp.status === 200) { return resp.data; } throw new Error(`Unable to get chunk: ${(0, error_1.getError)(resp)}`); } async getChunkData(offset) { const chunk = await this.getChunk(offset); const buf = ArweaveUtils.b64UrlToBuffer(chunk.chunk); return buf; } firstChunkOffset(offsetResponse) { return parseInt(offsetResponse.offset) - parseInt(offsetResponse.size) + 1; } async downloadChunkedData(id) { const offsetResponse = await this.getTransactionOffset(id); const size = parseInt(offsetResponse.size); const endOffset = parseInt(offsetResponse.offset); const startOffset = endOffset - size + 1; const data = new Uint8Array(size); let byte = 0; while (byte < size) { if (this.api.config.logging) { console.log(`[chunk] ${byte}/${size}`); } let chunkData; try { chunkData = await this.getChunkData(startOffset + byte); } catch (error) { console.error(`[chunk] Failed to fetch chunk at offset ${startOffset + byte}`); console.error(`[chunk] This could indicate that the chunk wasn't uploaded or hasn't yet seeded properly to a particular gateway/node`); } if (chunkData) { data.set(chunkData, byte); byte += chunkData.length; } else { throw new Error(`Couldn't complete data download at ${byte}/${size}`); } } return data; } } exports.default = Chunks;