All files / src/lib image-server.js

0% Statements 0/22
0% Branches 0/2
0% Functions 0/8
0% Lines 0/22

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                                                                                                                                                     
import { reject } from 'rsvp';
 
/**
 * Loads images from server. Settings are read from manifest.json
 * @class
 */
export class ImageServer {
  /**
   *
   * @param {{}} owner  An instance of {@link MiniMemory}
   */
  constructor(owner) {
    this.owner = owner;
    this.manifest = {};
    this.images = {};
    this.index = { from: 0, to: 0, card: 0 };
  }
 
  /**
   * get Images from server. Server path/url retrieved from manifest.json
   * @param {{}} options width, height and number of images to
   * be requested from server
   * @return {{fetch}} Returns Fetch Object that resolvest image-url response
   */
  getCardImages(options) {
    const self = this;
    self.index.to = options.imageCount;
    const host = self.owner.manifest.imageServer.list
      .replace(':from', self.index.from)
      .replace(':to', self.index.to)
      .replace(':cardId', self.index.card);
    self.index.from = options.imageCount;
    self.index.card = self.index.card + 1;
    return fetch(host)
      .then((response) => {
        if (!response.ok) {
          throw new Error(response.statusText);
        }
        return response.json();
      })
      .then((res) => {
        self.done(res, options);
      })
      .catch((e) => {
        reject(e);
      });
  }
  /**
   * Create Images (HTMLImageElement) and load images from server
   * @param {{}} res {images:[], card:[]}
   * @param {{}} options width, height and number of images to be
   * requested from server
   */
  done(res, options) {
    const self = this;
 
    self.owner.cardBack.addEventListener('load', (e) => {
      res.images.forEach((image) => {
        const img = document.createElement('img');
        img.src = self.owner.manifest.imageServer.image
          .replace(':width', options.width)
          .replace(':height', options.height)
          .replace(':path', image);
 
        self.owner.game.addImage(img);
      });
    });
 
    self.owner.cardBack.src = self.owner.manifest.imageServer.image
      .replace(':width', options.width)
      .replace(':height', options.height)
      .replace(':path', res.cards[0]);
  }
}