all files / lib/collection/ base.js

97.56% Statements 200/205
83.17% Branches 84/101
100% Functions 27/27
94.57% Lines 87/92
12 statements, 1 function, 7 branches Ignored     
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 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403                   66× 68×                                                     66×         32×           66×         16×     66×               66×         16×           66× 16×               16×         16×     16× 16×                     16×         16×     16×         16×       66×             66×         17×     66×         16×                               85× 17×     68× 130×                                           47×       47×   47× 47×   47×       47×     22× 22× 22× 47×   47×     47×   47×               22×                                                         12×                                                                                                                   20×     20×                                             20×         20×                                         46× 42×   42× 41×       46×      
import Promise from 'bluebird';
import fs from 'fs-extra';
Promise.promisifyAll(fs);
import path from 'path';
import isUndefined from 'lodash/isUndefined';
import isNumber from 'lodash/isNumber';
import isString from 'lodash/isString';
import sortBy from 'lodash/sortBy';
import some from 'lodash/some';
import each from 'lodash/each';
 
import log from '../log';
import filter from './filter';
import Plugin from '../plugin';
import CollectionPage from './page';
 
export default class CollectionBase {
  /**
   * Create a Collection instance.
   * @param {string} name The name of the collection.
   * @param {Object} collectionConfig Config object from config file.
   * @param {Function} getConfig Delegate function that returns config object.
   */
  constructor(name, collectionConfig = {}, getConfig) {
    if (isString(name) === false || name.length === 0) {
      throw new Error('Collection requires a name.');
    }
 
    /**
     * Unique ID of this Collection, currently its given name.
     * @type {string}
     */
    this.id = name;
 
    /**
     * The collection name. Must be unique.
     * @type {string}
     */
    this.name = name;
 
    /**
     * Data accesible to templates.
     * @type {Object}
     */
    this.data = {};
 
    /**
     * Gets config.
     * @type {Function}
     */
    this._getConfig = getConfig;
 
    if (!isUndefined(collectionConfig.path)) {
      /**
       * Path where items belong within the collection.
       * @type {string}
       */
      this.path = path.resolve(
        this._getConfig().get('path.source'),
        collectionConfig.path
      );
    }
 
    if (!isUndefined(collectionConfig.template)) {
      /**
       * What template to use when rendering an item within this collection.
       * @type {string}
       */
      this.template = collectionConfig.template;
    }
 
    if (!isUndefined(collectionConfig.metadata)) {
      /**
       * Metadata attribute to use to find which items are within the
       * collection.
       * @type {string}
       */
      this.metadata = collectionConfig.metadata;
    }
 
    if (!isUndefined(collectionConfig.sort)) {
      /**
       * Sorting configuration.
       * @type {Object}
       */
      this.sort = {
        key: collectionConfig.sort.key,
        order: collectionConfig.sort.order
      };
    }
 
    if (!isUndefined(collectionConfig.pagination)) {
      let paginationConfig = collectionConfig.pagination;
 
      /**
       * Pagination information.
       * @param {Object}
       */
      this.pagination = {};
 
      Eif (!isUndefined(paginationConfig.template)) {
        /**
         * What template to use when rendering a pagination page.
         * @type {string}
         */
        this.pagination.template = paginationConfig.template;
      }
 
      Eif (!isUndefined(paginationConfig.size)) {
        Iif (!isNumber(paginationConfig.size)) {
          throw new Error('Pagination size must be a number');
        }
 
        /**
         * Size of each pagination page.
         * @type {number}
         */
        this.pagination.size = paginationConfig.size;
      }
 
      Eif (!isUndefined(paginationConfig.permalink_index)) {
        /**
         * Permalink pagination index configuration.
         * @type {string}
         */
        this.pagination.permalinkIndex = paginationConfig.permalink_index;
      }
 
      Eif (!isUndefined(paginationConfig.permalink_page)) {
        /**
         * Permalink pagination page configuration.
         * @type {string}
         */
        this.pagination.permalinkPage = paginationConfig.permalink_page;
      }
    }
 
    if (!isUndefined(collectionConfig.permalink)) {
      /**
       * Permalink configuration.
       * @type {string}
       */
      this.permalink = collectionConfig.permalink;
    }
 
    if (!isUndefined(collectionConfig.static)) {
      /**
       * Whether this is a static collection.
       * @type {boolean}
       */
      this.static = collectionConfig.static;
    }
 
    if (!isUndefined(collectionConfig.filter)) {
      /**
       * What filters are applied to this collection.
       * @type {Object}
       */
      this.filter = collectionConfig.filter;
    }
 
    /**
     * Array of CollectionPage objects.
     * @type {Array.<CollectionPage>}
     */
    this.pages = [];
  }
 
  /**
   * Whether a file is being filtered by the configured filters.
   * @param {File} file File object.
   * @return {boolean} Whether this file should be filtered out.
   */
  isFiltered(file) {
    if (isUndefined(this.filter)) {
      return false;
    }
 
    return some(this.filter, (filterConfig, filterName) => {
      return filter[filterName](file, filterConfig);
    });
  }
 
  /**
   * Populate the Collection's files via file system path or metadata attribute.
   * @param {Object.<string, Files>} files All Files.
   * @param {Object.<string, CollectionBase>} collections Object of all
   *   collections.
   * @return {CollectionBase}
   */
  populate(files = {}, collections = {}) { // eslint-disable-line no-unused-vars
    return this;
  }
 
  /**
   * Create a CollectionPage instance.
   * @param {number} index Index of the page.
   * @param {string?} pageId Optionally give a custom ID for a CollectionPage.
   * @return {CollectionPage} CollectionPage instance.
   */
  createPage(index, pageId) {
    Iif (!isNumber(index)) {
      throw new Error('Must give an index when creating a CollectionPage.');
    }
 
    pageId = isUndefined(pageId) ? this.id : pageId;
 
    let page = new CollectionPage(pageId, index);
    page.setGetConfig(this._getConfig);
 
    page.permalink = index === 0 ?
      this.pagination.permalinkIndex :
      this.pagination.permalinkPage;
 
    return page;
  }
 
  _linkPages(shouldLinkPrevious, shouldLinkNext) {
    Eif (this.pages.length > 0) {
      this.pages.forEach((collectionPage, index) => {
        let previous = this.pages[index - 1];
 
        if (shouldLinkPrevious(previous, collectionPage)) {
          collectionPage.setPreviousPage(previous);
        }
 
        let next = this.pages[index + 1];
 
        if (shouldLinkNext(next, collectionPage)) {
          collectionPage.setNextPage(next);
        }
      });
    }
 
    // Add data to template accessible object.
    this.data.pages = this.pages.map(page => page.data);
 
    return this;
  }
 
  /**
   * Writes a given File object within the collection to the file system.
   * @param {File} file File instance.
   * @param {Object} siteData Site wide data.
   * @return {Promise} Promise object, resolved when file is written to disk.
   */
  writeFile(file, siteData) {
    if (isUndefined(this.template)) {
      log.error('No template found when trying to write file in Collection ' +
        `${this.id} for ${file.id}`);
      return Promise.resolve();
    }
 
    return CollectionBase.renderAndWriteFile(
      file,
      this.template,
      siteData,
      Plugin.Event.file.beforeRender,
      Plugin.Event.file.afterRender
    );
  }
 
  /**
   * Writes a given CollectionPage object within the collection to the file
   * system.
   * @param {CollectionPage} collectionPage CollectionPage instance.
   * @param {Object} siteData Site wide data.
   * @return {Promise} Promise object, resolved when file is written to disk.
   */
  writePage(collectionPage, siteData) {
    return CollectionBase.renderAndWriteFile(
      collectionPage,
      this.pagination.template,
      siteData,
      Plugin.Event.page.beforeRender,
      Plugin.Event.page.afterRender
    );
  }
 
  /**
   * Writes both files and pages that are in this collection.
   * @param {Object} siteData Site wide data that is shared on all rendered
   *  files.
   * @return {Promise}
   */
  async write(siteData) {
    let result;
 
    let filePromises = [];
    // If we're writing individual files then write them.
    if (this.files) {
      each(this.files, file => {
        filePromises.push(this.writeFile(file, siteData));
      });
    }
 
    try {
      result = await Promise.all(filePromises);
    } catch (e) {
      log.error(e.stack);
      throw e;
    }
 
    let pagePromises = [];
    // Write CollectionPage files.
    if (this.pages.length) {
      this.pages.forEach(collectionPage => {
        pagePromises.push(this.writePage(collectionPage, siteData));
      });
    }
 
    try {
      result = await Promise.all(pagePromises);
    } catch (e) {
      log.error(e.stack);
      throw e;
    }
 
    return result;
  }
 
  /**
   * Write a file to the file system. Calls all plugin events.
   * @param {(File|CollectionPage)} file File or CollectionPage object.
   * @param {string} template Which template template to use.
   * @param {Object} siteData Site wide template data.
   * @param {Plugin.Event} eventBefore Which event handler to process before
   *   rendering the file.
   * @param {Plugin.Event} eventAfter Which event handler to process after
   *   rendering the file.
   * @return {Promise}
   */
  static async renderAndWriteFile(file, template, siteData,
    eventBefore, eventAfter) {
 
    if (eventBefore) {
      await Plugin.processEventHandlers(eventBefore, file);
    }
 
    let renderedFile = file.render(template, siteData);
 
    if (eventAfter) {
      [file, renderedFile] = await Plugin.processEventHandlers(
        eventAfter,
        file,
        renderedFile
      );
    }
 
    return CollectionBase.writeToFileSystem(
      file,
      renderedFile
    );
  }
 
  /**
   * Wrapper for writing to the file system.
   * @param {(File|CollectionPage)} file File or CollectionPage object.
   * @param {string} content Content of file.
   * @param {string} encoding What encoding to use when writing file.
   * @return {Promise}
   */
  static async writeToFileSystem(file, content, encoding = 'utf8') {
    // log.info('Writing file to %s', file.destination);
 
    [file, content] = await Plugin.processEventHandlers(
      Plugin.Event.collection.beforeWrite,
      file, content
    );
 
    let result = await fs.outputFileAsync(
      file.destination,
      content,
      encoding
    );
 
    await Plugin.processEventHandlers(
      Plugin.Event.collection.afterWrite,
      file, content
    );
 
    return result;
  }
 
  /**
   * Sorts files according to a sort config object.
   * @param {Array.<File>} files Array of File objects.
   * @param {Object} sortConfig Sort config object.
   * @return {Array.<file>} Sorted files.
   */
  static sortFiles(files, sortConfig) {
    if (sortConfig && sortConfig.key) {
      files = sortBy(files, sortConfig.key);
 
      if (sortConfig.order === 'descending') {
        files.reverse();
      }
    }
 
    return files;
  }
}