All files / src/common api.ts

90% Statements 9/10
83.33% Branches 5/6
100% Functions 1/1
100% Lines 9/9

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                1x                       4x 4x   4x       1x 1x 1x     4x 4x    
import * as dns from '../dns'
import { setup } from '../setup/internal'
 
 
const didCache: {
  did: string | null
  host: string | null
  lastFetched: number
} = {
  did: null,
  host: null,
  lastFetched: 0,
}
 
 
/**
 * Lookup the DID of a Fission API.
 * This function caches the DID for 3 hours.
 */
export async function did(): Promise<string> {
  const host = setup.endpoints.api.replace(/^https?:\/\//, '').replace(/\/$/, '')
  const now = Date.now() // in milliseconds
 
  if (
    didCache.host !== host ||
    didCache.lastFetched + 1000 * 60 * 60 * 3 <= now
  ) {
    didCache.did = await dns.lookupTxtRecord('_did.' + host)
    didCache.host = host
    didCache.lastFetched = now
  }
 
  Iif (!didCache.did) throw new Error("Couldn't get the Fission API DID")
  return didCache.did
}