Home Reference Source

src/importer.js

import isArray from 'lodash/isArray'
import vRead from 'vinyl-read'
import { propertyHider } from './util'

const { defineProperty } = Object

import { DefaultPatterns } from './document'

export default class DocumentImporter {
  static patterns = DefaultPatterns;

  static create (base, options = {}) {
    if (typeof options === 'string') {
      options = {
        patterns: [options],
        base
      }
    }

    if (isArray(options)) {
      options = {
        patterns: options,
        base
      }
    }

    const importer = new DocumentImporter(base, {
      ...options
    })

    return importer
  }

  constructor (base = process.cwd(), options = {}) {
    const hide = this.hide = propertyHider(this)

    if (typeof base !== 'string') {
      throw('Document Importers must be created with a base path')
    }

    hide('base', base)
    hide('options', options)
    hide('patterns', options.patterns || DefaultPatterns)

    let status = 'CREATED'

    defineProperty(this, 'status', {
      configurable: false,
      get: () => status,
      set: ((newValue) => status = newValue)
    })
  }

  readFilesSync (includeContents) {
    return vRead.sync(this.patterns, {
      base: this.base,
      read: !!includeContents,
    })
  }

  async readFiles (includeContents) {
    const _files = await vRead(this.patterns, {
      base: this.base,
      read: !!includeContents,
    })

    return _files
  }
}