const State = require('../State') const axios = require('axios') class DownloadState extends State { static get services() { return [...super.services, 'output'] } async apply() { if ( !(await this.check()) ) { const path = await this._path() if ( !this._config.method ) this._config.method = 'get' else this._config.method = this._config.method.toLowerCase() if ( !this._config.source ) throw new Error('Missing source config for DownloadState.') try { const res = await axios({ method: this._config.method, url: this._config.source, responseType: 'stream', }) const write_stream = await path.open_write_stream() await res.data.pipe(write_stream) } catch(e) { this.output.error('Error encountered while fetching data for DownloadState.') throw e } } } async check() { const path = await this._path() await path.classify() return path.is_file() } async reverse() { if ( await this.check() ) { const path = await this._path() await path.unlink() } } async _path() { if ( !this._config.path ) throw new Error('Missing path config for DownloadState.') return this._host.get_path(this._config.path) } failure_message() { return `The downloaded file "${this._config.path}" does not exist on host "${this._host.name}."` } check_message() { return this.failure_message() } } module.exports = exports = DownloadState