All files / src/client index.ts

87.71% Statements 50/57
61.9% Branches 13/21
83.33% Functions 15/18
87.5% Lines 49/56

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 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 1801x 1x 1x 1x   1x 1x                     1x   1x           1x               4x 4x             4x       4x           4x 4x         4x             4x             1x 1x             1x     1x       1x       2x         6x                           4x 4x         4x 4x 5x   4x 3x       4x             1x 1x       4x       4x 3x 3x     4x 4x             1x 1x     2x 2x 1x   1x                     2x 2x     1x      
import fetch from 'isomorphic-fetch'
import jsonBigint from 'json-bigint'
import WebSocket from 'isomorphic-ws'
import {createPatch} from 'rfc6902'
import {AddOperation, RemoveOperation, ReplaceOperation} from 'rfc6902/diff'
import {createClient, Client as SubscriptionClient} from '../../graphql-ws/src'
import {
  Network,
  Environment,
  ClientOptions,
  Client,
  FlexibleRequestBody,
  SubscriptionHandlers,
  PatchedSubscriptionHandlers,
  PatchOperation,
  ObservableSubscription,
} from '../types'
import {formatRequestBody, resolveJsonPointer} from './utils'
 
const {parse} = jsonBigint({
  useNativeBigInt: true,
})
 
// generate types
//https://github.com/evanw/esbuild/issues/95#issuecomment-1007485134
export default class HgraphClient implements Client {
  endpoint: string
  headers: Record<string, string>
  subscriptionClient: SubscriptionClient
  private subscriptions: ObservableSubscription[]
 
  constructor(options?: ClientOptions) {
    // add to BigInt prototype for JSON.stringify
    if (options?.patchBigIntToJSON !== false) {
      BigInt.prototype['toJSON'] = function () {
        if (Number.MIN_SAFE_INTEGER < this && this < Number.MAX_SAFE_INTEGER)
          return Number(this)
        else return this.toString()
      }
    }
 
    this.endpoint = `https://${
      options?.network || Network.HederaTestnet
    }.api.hgraph.${options?.environment || Environment.Development}/v1/graphql`
 
    this.headers = {
      'content-type': 'application/json',
      ...(options?.headers ?? {}),
      ...(options?.token && {authorization: `Bearer ${options.token}`}),
    }
 
    const identifier = options?.token || options?.headers['x-api-key']
    const url = identifier
      ? this.endpoint
          .replace('https', 'wss')
          .replace('graphql', `${encodeURIComponent(identifier)}/graphql`)
      : this.endpoint.replace('https', 'wss')
    this.subscriptionClient = createClient({
      url,
      webSocketImpl: WebSocket,
      connectionParams: this.headers,
      jsonParse: parse,
    })
 
    this.subscriptions = []
  }
 
  async query(
    flexibleRequestBody: FlexibleRequestBody,
    abortSignal?: AbortSignal
  ) {
    const body = formatRequestBody(flexibleRequestBody)
    const response = await fetch(this.endpoint, {
      method: 'POST',
      headers: this.headers,
      body: JSON.stringify(body),
      signal: abortSignal,
    })
 
    Iif (!response.ok)
      throw new Error(`${response.status} - ${response.statusText}`)
 
    return parse(await response.text())
  }
 
  removeSubscription(observable: ObservableSubscription) {
    observable.unsubscribe()
  }
 
  removeAllSubscriptions() {
    this.getSubscriptions().forEach((observable) => observable.unsubscribe())
  }
 
  getSubscriptions() {
    //copy of original array
    return [...this.subscriptions]
  }
 
  /**
   * @deprecated Use {@link getSubscriptions} instead.
   */
  getSubscribtions() {
    return this.getSubscriptions()
  }
 
  subscribe(
    flexibleRequestBody: FlexibleRequestBody,
    handlers: SubscriptionHandlers
  ) {
    const body = formatRequestBody(flexibleRequestBody)
    const observableSubscription: ObservableSubscription = {
      handlers,
      unsubscribe: null,
    }
 
    const cleanUpSubscription = (observable: ObservableSubscription) => {
      this.subscriptions = this.subscriptions.filter(
        (subscription) => subscription != observable
      )
      observableSubscription.unsubscribe = () => {
        throw new Error('This subscription has already been unsubscribed')
      }
    }
 
    const observableHandlers: SubscriptionHandlers = {
      ...handlers,
      error: (errors) => {
        cleanUpSubscription(observableSubscription)
        observableSubscription.handlers.error(errors)
      },
      complete: () => {
        cleanUpSubscription(observableSubscription)
        observableSubscription.handlers.complete()
      },
    }
 
    const unsubscribe = this.subscriptionClient.subscribe(
      body,
      observableHandlers
    )
    observableSubscription.unsubscribe = () => {
      cleanUpSubscription(observableSubscription)
      unsubscribe()
    }
 
    this.subscriptions.push(observableSubscription)
    return observableSubscription
  }
 
  patchedSubscribe(
    flexibleRequestBody: FlexibleRequestBody,
    handlers: PatchedSubscriptionHandlers
  ) {
    let prevData = null
    const patchedHandlers: SubscriptionHandlers = {
      ...handlers,
      next: (data) => {
        let patches: PatchOperation[] = []
        if (prevData) {
          patches = createPatch(prevData, data).map(
            (operation: AddOperation | ReplaceOperation | RemoveOperation) => {
              return {
                ...operation,
                //add value to remove operation
                value:
                  operation.op == 'remove'
                    ? resolveJsonPointer(prevData, operation.path)
                    : operation.value,
              }
            }
          )
        }
        prevData = data
        handlers.next(data, patches)
      },
    }
    return this.subscribe(flexibleRequestBody, patchedHandlers)
  }
}