UNPKG

@ethersphere/bee-js

Version:
86 lines 2.81 kB
import { Optional, Types } from 'cafe-utility'; import { Bytes } from "../utils/bytes.js"; import { prepareRequestHeaders } from "../utils/headers.js"; import { http } from "../utils/http.js"; import { makeTagUid, prepareDownloadOptions } from "../utils/type.js"; import { Reference } from "../utils/typed-bytes.js"; const endpoint = 'bytes'; /** * Upload data to a Bee node * * @param requestOptions Options for making requests * @param data Data to be uploaded * @param postageBatchId Postage BatchId that will be assigned to uploaded data * @param options Additional options like tag, encryption, pinning */ export async function upload(requestOptions, data, postageBatchId, options) { const response = await http(requestOptions, { url: endpoint, method: 'post', responseType: 'json', data, headers: { 'content-type': 'application/octet-stream', ...prepareRequestHeaders(postageBatchId, options) } }); const body = Types.asObject(response.data, { name: 'response.data' }); return { reference: new Reference(Types.asHexString(body.reference)), tagUid: response.headers['swarm-tag'] ? makeTagUid(response.headers['swarm-tag']) : undefined, historyAddress: response.headers['swarm-act-history-address'] ? Optional.of(new Reference(response.headers['swarm-act-history-address'])) : Optional.empty() }; } /** * Requests content length for a reference * * @param requestOptions Options for making requests * @param hash Bee content reference */ export async function head(requestOptions, reference) { reference = new Reference(reference); const response = await http(requestOptions, { url: `${endpoint}/${reference}`, method: 'head', responseType: 'json' }); return { contentLength: parseInt(response.headers['content-length']) }; } /** * Download data as a byte array * * @param requestOptions Options for making requests * @param hash Bee content reference */ export async function download(requestOptions, resource, options) { if (options) { options = prepareDownloadOptions(options); } const response = await http(requestOptions, { responseType: 'arraybuffer', url: `${endpoint}/${resource}`, headers: prepareRequestHeaders(null, options) }); return new Bytes(response.data); } /** * Download data as a readable stream * * @param requestOptions Options for making requests * @param hash Bee content reference */ export async function downloadReadable(requestOptions, resource, options) { if (options) { options = prepareDownloadOptions(options); } const response = await http(requestOptions, { responseType: 'stream', url: `${endpoint}/${resource}`, headers: prepareRequestHeaders(null, options) }); return response.data; }