All files / src/modules pss.ts

91.66% Statements 11/12
0% Branches 0/1
100% Functions 2/2
91.66% Lines 11/12

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 5633x 33x   33x 33x     33x                         33x               1x                               33x 1x   1x       1x        
import { System } from 'cafe-utility'
import WebSocket from 'isomorphic-ws'
import type { BeeRequestOptions } from '../types'
import { prepareRequestHeaders } from '../utils/headers'
import { http } from '../utils/http'
import { BatchId, PublicKey, Topic } from '../utils/typed-bytes'
 
const endpoint = 'pss'
 
/**
 * Send to recipient or target with Postal Service for Swarm
 *
 * @param requestOptions Options for making requests
 * @param topic Topic name
 * @param target Target message address prefix
 * @param data
 * @param postageBatchId Postage BatchId that will be assigned to sent message
 * @param recipient Recipient public key
 *
 */
export async function send(
  requestOptions: BeeRequestOptions,
  topic: Topic,
  target: string,
  data: string | Uint8Array,
  postageBatchId: BatchId,
  recipient?: PublicKey,
): Promise<void> {
  await http<unknown>(requestOptions, {
    method: 'post',
    url: `${endpoint}/send/${topic}/${target}`,
    data,
    responseType: 'json',
    params: { recipient },
    headers: prepareRequestHeaders(postageBatchId),
  })
}
 
/**
 * Subscribe for messages on the given topic
 *
 * @param url Bee node URL
 * @param topic Topic name
 */
export function subscribe(url: string, topic: Topic, headers?: Record<string, string>): WebSocket {
  const wsUrl = url.replace(/^http/i, 'ws')
 
  Iif (System.whereAmI() === 'browser') {
    return new WebSocket(`${wsUrl}/${endpoint}/subscribe/${topic.toHex()}`)
  }
 
  return new WebSocket(`${wsUrl}/${endpoint}/subscribe/${topic.toHex()}`, {
    headers,
  })
}