-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: adds support for node stream as source
- Loading branch information
Showing
4 changed files
with
78 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,62 @@ | ||
import es from 'event-stream'; | ||
import split from 'split2'; | ||
|
||
export default function streamReaderFactory(indexer, stream, transform, splitRegex, verbose) { | ||
function startIndex() { | ||
let finished = false; | ||
|
||
const s = stream.pipe(split(splitRegex)).pipe( | ||
es | ||
.mapSync(line => { | ||
try { | ||
// skip empty lines | ||
if (line === '') { | ||
return; | ||
} | ||
|
||
const doc = | ||
typeof transform === 'function' ? JSON.stringify(transform(JSON.parse(line))) : line; | ||
|
||
// if doc is undefined we'll skip indexing it | ||
if (typeof doc === 'undefined') { | ||
s.resume(); | ||
return; | ||
} | ||
|
||
// the transform callback may return an array of docs so we can emit | ||
// multiple docs from a single line | ||
if (Array.isArray(doc)) { | ||
doc.forEach(d => indexer.add(d)); | ||
return; | ||
} | ||
|
||
indexer.add(doc); | ||
} catch (e) { | ||
console.log('error', e); | ||
} | ||
}) | ||
.on('error', err => { | ||
console.log('Error while reading file.', err); | ||
}) | ||
.on('end', () => { | ||
if (verbose) console.log('Read entire stream.'); | ||
indexer.finish(); | ||
finished = true; | ||
}), | ||
); | ||
|
||
indexer.queueEmitter.on('pause', () => { | ||
if (finished) return; | ||
s.pause(); | ||
}); | ||
|
||
indexer.queueEmitter.on('resume', () => { | ||
if (finished) return; | ||
s.resume(); | ||
}); | ||
} | ||
|
||
return () => { | ||
startIndex(); | ||
}; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters