All files / src/loader blob-loader.ts

0% Statements 0/42
0% Branches 0/18
0% Functions 0/19
0% Lines 0/42

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                                                                                                                                                                                                                                                                                                           
import * as dom from '../dom/dom';
 
/**
 * A class that fetches a bunch of blobs.
 *
 * Here is an example of using the blob loader to fetch images.
 * const myImages = [
 *  'http://mydomain.com/dog.png',
 *  'http://mydomain.com/cat.png'
 *  'http://mydomain.com/cow.jpg'
 * ];
 *
 * const blobLoader = new blobLoader();
 *
 * // Loads images.
 * await results = blobLoader.load();
 *
 * // The source of the image is the key.
 * results['http://mydomain.com/dog.png']; // DOG blob.
 * results['http://mydomain.com/cat.png']; // Cat blob.
 *
 * const image = dom.makeImageFromBlob(blob);
 *
 * // Use the image.
 * canvas.drawImage(image);
 *
 * // Now delete it from memory.
 * dom.deleteImage(image);
 *
 * // Later
 * blobLoader.dispose();
 *
 * ```
 */
export class BlobLoader {
  public imageSources: Array<string>;
 
  /**
   * An object with the key as the source URL and value as blob.
   */
  private blobs: Record<string, Blob>;
 
  /**
   * An object with the key as the source URL and value as base64 images.
   */
  private images64: Record<string, HTMLImageElement>;
 
  /**
   * The number of times to refetch an image if unsuccessful.
   */
  public maxRetries: number;
 
  constructor(imageSources: Array<string>) {
    this.imageSources = imageSources;
    this.blobs = {};
    this.images64 = {};
    this.maxRetries = 3;
  }
 
  load(): Promise<Record<string, Blob>> {
    return new Promise((resolve) => {
      if (!this.imageSources) {
        resolve(this.blobs);
      }
      const promises = this.imageSources.map((source) => {
        return this.loadBlob(source);
      });
 
      Promise.all(promises).then(() => {
        resolve(this.blobs);
      });
    });
  }
 
  loadBlob(source: string, retryCount = 0): Promise<Blob | undefined> {
    return new Promise((resolve) => {
      fetch(source)
        .then((response) => {
          // If status was not okay retry.
          if (!response.ok) {
            retryCount++;
            if (retryCount >= this.maxRetries) {
              throw new Error(`failed after ${retryCount} tries`);
            } else {
              return this.loadBlob(source, retryCount);
            }
          } else {
            return response.blob();
          }
        })
        .then((response) => {
          if (this.blobs && response) {
            this.blobs[source] = response;
          }
          resolve(response);
        });
    });
  }
 
  /**
   * Loads the requested images as Base64 images.
   */
  loadBase64Images() {
    return new Promise((resolve) => {
      const promises = this.imageSources.map((source) => {
        return this.loadBlobAsBase64Image(source);
      });
 
      Promise.all(promises).then(() => {
        resolve(this.images64);
      });
    });
  }
 
  loadBlobAsBase64Image(
    source: string,
    retryCount = 0
  ): Promise<Blob | undefined | void> {
    return new Promise((resolve, reject) => {
      fetch(source)
        .then((response) => {
          // If status was not okay retry.
          if (!response.ok) {
            retryCount++;
            if (retryCount >= this.maxRetries) {
              reject(`failed after ${retryCount} tries`);
            }
            return this.loadBlobAsBase64Image(source, retryCount);
          } else {
            return response.blob();
          }
        })
        .then((response) => {
          if (response) {
            dom.makeBase64ImageFromBlob(response).then((image) => {
              this.images64[source] = image;
              resolve(response);
            });
          }
        });
    });
  }
 
  dispose() {
    this.imageSources = [];
    this.images64 = {};
    this.blobs = {};
  }
}