All files / src/profiles/profileSchemas personZoneFiles.ts

56.67% Statements 17/30
100% Branches 2/2
80% Functions 4/5
56.67% Lines 17/30

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  1x   1x 1x 1x 1x                   1x       1x   1x                 1x   1x                             1x 1x 1x   1x 1x 1x   1x                    
// @ts-ignore: Could not find a declaration file for module
import { parseZoneFile } from 'zone-file'
 
import { Person } from './person'
import { getTokenFileUrl } from '../profileZoneFiles'
import { extractProfile } from '../profileTokens'
import { fetchPrivate } from '../../fetchUtil'
 
/**
 * 
 * @param zoneFile 
 * @param publicKeyOrAddress 
 * @param callback 
 * 
 * @ignore
 */
export function resolveZoneFileToPerson(
  zoneFile: any, 
  publicKeyOrAddress: string, 
  callback: (profile: any) => void) {
  let zoneFileJson = null
  try {
    zoneFileJson = parseZoneFile(zoneFile)
    if (!zoneFileJson.hasOwnProperty('$origin')) {
      zoneFileJson = null
      throw new Error('zone file is missing an origin')
    }
  } catch (e) {
    console.error(e)
  }
 
  let tokenFileUrl = null
  if (zoneFileJson && Object.keys(zoneFileJson).length > 0) {
    tokenFileUrl = getTokenFileUrl(zoneFileJson)
  } else {
    let profile = null
    try {
      profile = JSON.parse(zoneFile)
      const person = Person.fromLegacyFormat(profile)
      profile = person.profile()
    } catch (error) {
      console.warn(error)
    }
    callback(profile)
    return
  }
 
  if (tokenFileUrl) {
    fetchPrivate(tokenFileUrl)
      .then(response => response.text())
      .then(responseText => JSON.parse(responseText))
      .then((responseJson) => {
        const tokenRecords = responseJson
        const token = tokenRecords[0].token
        const profile = extractProfile(token, publicKeyOrAddress)
 
        callback(profile)
      })
      .catch((error) => {
        console.warn(error)
      })
  } else {
    console.warn('Token file url not found')
    callback({})
  }
}