(resourceMapper, copyToUri, copyFromUri)
| 29 | * @return A promise resolving when the copy operation is finished |
| 30 | */ |
| 31 | export default function copy (resourceMapper, copyToUri, copyFromUri) { |
| 32 | return new Promise((resolve, reject) => { |
| 33 | const request = /^https:/.test(copyFromUri) ? https : http |
| 34 | |
| 35 | const options = { |
| 36 | rejectUnauthorized: false // Allow self-signed certificates for internal requests |
| 37 | } |
| 38 | |
| 39 | request.get(copyFromUri, options) |
| 40 | .on('error', function (err) { |
| 41 | debug('COPY -- Error requesting source file: ' + err) |
| 42 | this.end() |
| 43 | return reject(new Error('Error writing data: ' + err)) |
| 44 | }) |
| 45 | .on('response', function (response) { |
| 46 | if (response.statusCode !== 200) { |
| 47 | debug('COPY -- HTTP error reading source file: ' + response.statusMessage) |
| 48 | this.end() |
| 49 | const error = new Error('Error reading source file: ' + response.statusMessage) |
| 50 | error.statusCode = response.statusCode |
| 51 | return reject(error) |
| 52 | } |
| 53 | // Grab the content type from the source |
| 54 | const contentType = getContentType(response.headers) |
| 55 | resourceMapper.mapUrlToFile({ url: copyToUri, createIfNotExists: true, contentType }) |
| 56 | .then(({ path: copyToPath }) => { |
| 57 | ensureDir(path.dirname(copyToPath)) |
| 58 | .then(() => { |
| 59 | const destinationStream = fs.createWriteStream(copyToPath) |
| 60 | .on('error', function (err) { |
| 61 | cleanupFileStream(this) |
| 62 | return reject(new Error('Error writing data: ' + err)) |
| 63 | }) |
| 64 | .on('finish', function () { |
| 65 | // Success |
| 66 | debug('COPY -- Wrote data to: ' + copyToPath) |
| 67 | resolve() |
| 68 | }) |
| 69 | response.pipe(destinationStream) |
| 70 | }) |
| 71 | .catch(err => { |
| 72 | debug('COPY -- Error creating destination directory: ' + err) |
| 73 | return reject(new Error('Failed to create the path to the destination resource: ' + err)) |
| 74 | }) |
| 75 | }) |
| 76 | .catch((err) => { |
| 77 | debug('COPY -- mapUrlToFile error: ' + err) |
| 78 | reject(HTTPError(500, 'Could not find target file to copy')) |
| 79 | }) |
| 80 | }) |
| 81 | }) |
| 82 | } |
nothing calls this directly
no test coverage detected