All files / src/parsers/helpers convertHashlink.ts

100% Statements 18/18
100% Branches 0/0
100% Functions 5/5
100% Lines 16/16

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      1x 1x   1x       1x   1x 1x   1x 1x 1x         134x 134x 134x       64x     1x 1x   64x    
import type { HashlinkVerifier, HashlinkModel } from '@blockcerts/hashlink-verifier';
 
function replaceHashlinksWithUrls (display: string, urls: string[], hashlinks: string[]): string {
  urls.forEach((url, i) => {
    display = display.replace(hashlinks[i], url);
  });
  return display;
}
 
async function decodeHashlinks (hashlinks: string[], hl: HashlinkVerifier): Promise<string[]> {
  const decoded: HashlinkModel[] = await Promise.all(
    hashlinks.map(async (hashlink): Promise<HashlinkModel> => {
      const decoded = await hl.decode(hashlink);
      return decoded;
    }));
  return decoded.reduce(function (urls, decodedHashlink: HashlinkModel) {
    urls.push(decodedHashlink.meta.url[0]);
    return urls;
  }, []);
}
 
export function getHashlinksFrom (display: string): string[] {
  const hashlinkTest = /hl:{1}[a-zA-Z0-9]+:{1}[a-zA-Z0-9]+/gm;
  const hashlinksMatch = [...display.matchAll(hashlinkTest)];
  return hashlinksMatch.map(match => match[0]).filter(value => !!value);
}
 
export default async function convertHashlink (display: string, hl: HashlinkVerifier): Promise<string> {
  const hashlinks = getHashlinksFrom(display);
 
  if (hashlinks.length) {
    const urls: string[] = await decodeHashlinks(hashlinks, hl);
    display = replaceHashlinksWithUrls(display, urls, hashlinks);
  }
  return display;
}