|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +const path = require('path'); |
| 4 | +const _ = require('lodash'); |
| 5 | +const Promise = require('bluebird'); |
| 6 | + |
| 7 | +const fs = require('fs-extra'); |
| 8 | +const outputFileAsync = Promise.promisify(fs.outputFile); |
| 9 | +const removeAsync = Promise.promisify(fs.remove); |
| 10 | + |
| 11 | +const supportedOptions = [ 'directory' ]; |
| 12 | + |
| 13 | +class ResourceSaver { |
| 14 | + constructor (options) { |
| 15 | + this.options = _.pick(options, supportedOptions); |
| 16 | + |
| 17 | + if (!this.options.directory || typeof this.options.directory !== 'string') { |
| 18 | + throw new Error('Incorrect directory ' + this.options.directory); |
| 19 | + } |
| 20 | + |
| 21 | + this.absoluteDirectoryPath = path.resolve(process.cwd(), this.options.directory); |
| 22 | + |
| 23 | + if (exists(this.absoluteDirectoryPath)) { |
| 24 | + throw new Error('Directory ' + this.absoluteDirectoryPath + ' exists'); |
| 25 | + } |
| 26 | + |
| 27 | + this.loadedResources = []; |
| 28 | + } |
| 29 | + |
| 30 | + /** |
| 31 | + * Save resource to file system |
| 32 | + * @param {Resource} resource |
| 33 | + * @returns {Promise} |
| 34 | + */ |
| 35 | + saveResource (resource) { |
| 36 | + const filename = path.join(this.absoluteDirectoryPath, resource.getFilename()); |
| 37 | + const text = resource.getText(); |
| 38 | + return outputFileAsync(filename, text, { encoding: 'binary' }).then(() => { |
| 39 | + this.loadedResources.push(resource); |
| 40 | + }); |
| 41 | + } |
| 42 | + |
| 43 | + /** |
| 44 | + * Remove all files that were saved before |
| 45 | + * @returns {Promise} |
| 46 | + */ |
| 47 | + errorCleanup () { |
| 48 | + if (!_.isEmpty(this.loadedResources)) { |
| 49 | + return removeAsync(this.absoluteDirectoryPath); |
| 50 | + } |
| 51 | + return Promise.resolve(); |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +function exists (path) { |
| 56 | + let exists; |
| 57 | + try { |
| 58 | + if (fs.statSync(path)) { |
| 59 | + exists = true; |
| 60 | + } |
| 61 | + } catch (e) { |
| 62 | + if (e.code === 'ENOENT') { |
| 63 | + exists = false; |
| 64 | + } else { |
| 65 | + throw e; |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + return exists; |
| 70 | +} |
| 71 | + |
| 72 | +module.exports = ResourceSaver; |
0 commit comments