Skip to content

Commit

Permalink
refactor(FileWriter): Flipped _write implementation to async/await
Browse files Browse the repository at this point in the history
  • Loading branch information
jezhiggins committed Apr 27, 2020
1 parent 12f1172 commit bbd24d4
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 26 deletions.
10 changes: 2 additions & 8 deletions lib/File-builder.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,13 +39,7 @@ class FileBuilder {
return dirPath
}

writeStreamInfo (incomingCsvLine, callback) {
this.writeStreamInfoAsync(incomingCsvLine)
.then(info => callback(null, info))
.catch(err => callback(err))
}

async writeStreamInfoAsync (incomingCsvLine) {
async findStreamInfo (incomingCsvLine) {
const dirPath = this.dirPathFromCsvLine(incomingCsvLine)
const fileConfig = this.fileConfigFromCsvLine(incomingCsvLine)
const key = dirPath + '/' + fileConfig.filename + '.csv'
Expand All @@ -58,7 +52,7 @@ class FileBuilder {
this.files[key] = info

return info
} // writeStreamInfo
} // findStreamInfo

async createWriteStream (key, dirPath, fileConfig) {
if (this.knownDirs.indexOf(dirPath) === -1) {
Expand Down
33 changes: 16 additions & 17 deletions lib/Writer.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const Writable = require('stream').Writable
const writeToStream = require('./write-to-stream')

class FileWriter extends Writable {
constructor (fileBuilder, options) {
Expand All @@ -15,28 +16,26 @@ class FileWriter extends Writable {
}

_write (incomingCsvLine, encoding, callback) {
this.doWrite(incomingCsvLine)
.then(() => callback())
.catch(err => callback(err))
}

async doWrite (incomingCsvLine) {
if (!(this.firstLine && this.skipFirstLine)) {
this.firstLine = false
this.fileBuilder.writeStreamInfo(incomingCsvLine, function (err, info) {
if (err) {
callback(err)
} else {
info.writeStream.write(info.transformer.transform(incomingCsvLine), function (err) {
if (err) {
callback(err)
} else {
info.count += 1
callback()
}
})
}
})

const info = await this.fileBuilder.findStreamInfo(incomingCsvLine)
await writeToStream(
info.writeStream,
info.transformer.transform(incomingCsvLine)
)
info.count += 1
} else {
// Skipped this first line
this.firstLine = false
callback()
}
}
}
} // _write
} // FileWriter

module.exports = FileWriter
2 changes: 1 addition & 1 deletion lib/write-to-stream.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
async function writeToStream(stream, output) {
async function writeToStream (stream, output) {
return new Promise((resolve, reject) => {
stream.write(
output,
Expand Down

0 comments on commit bbd24d4

Please sign in to comment.