All files / src/modules chunk.ts

100% Statements 14/14
50% Branches 2/4
100% Functions 2/2
100% Lines 14/14

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 7233x   33x 33x 33x 33x   33x                           33x           16x                     16x   16x                               33x         20x   20x           17x    
import { Optional, Types } from 'cafe-utility'
import type { BeeRequestOptions, DownloadOptions, EnvelopeWithBatchId, UploadOptions, UploadResult } from '../types'
import { prepareRequestHeaders } from '../utils/headers'
import { http } from '../utils/http'
import { makeTagUid } from '../utils/type'
import { BatchId, Reference } from '../utils/typed-bytes'
 
const endpoint = 'chunks'
 
/**
 * Upload chunk to a Bee node
 *
 * The chunk data consists of 8 byte span and up to 4096 bytes of payload data.
 * The span stores the length of the payload in uint64 little endian encoding.
 * Upload expects the chuck data to be set accordingly.
 *
 * @param requestOptions Options for making requests
 * @param data Chunk data to be uploaded
 * @param stamp BatchId or marshaled stamp to be used for the upload
 * @param options Additional options like tag, encryption, pinning
 */
export async function upload(
  requestOptions: BeeRequestOptions,
  data: Uint8Array,
  stamp: EnvelopeWithBatchId | BatchId | Uint8Array | string,
  options?: UploadOptions,
): Promise<UploadResult> {
  const response = await http<unknown>(requestOptions, {
    method: 'post',
    url: `${endpoint}`,
    data,
    headers: {
      'content-type': 'application/octet-stream',
      ...prepareRequestHeaders(stamp, options),
    },
    responseType: 'json',
  })
 
  const body = Types.asObject(response.data, { name: 'response.data' })
 
  return {
    reference: new Reference(Types.asString(body.reference, { name: '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(),
  }
}
 
/**
 * Download chunk data as a byte array
 *
 * @param requestOptions Options for making requests
 * @param hash Bee content reference
 *
 */
export async function download(
  requestOptions: BeeRequestOptions,
  reference: Reference | string | Uint8Array,
  options?: DownloadOptions,
): Promise<Uint8Array> {
  reference = new Reference(reference)
 
  const response = await http<ArrayBuffer>(requestOptions, {
    responseType: 'arraybuffer',
    url: `${endpoint}/${reference}`,
    headers: prepareRequestHeaders(null, options),
  })
 
  return new Uint8Array(response.data)
}