smartstream/ts/index.ts

106 lines
2.2 KiB
TypeScript
Raw Normal View History

2016-09-25 12:00:16 +00:00
import * as plugins from './smartstream.plugins'
2017-06-30 16:32:32 +00:00
// interfaces
2017-03-04 13:26:10 +00:00
import { Transform } from 'stream'
2016-09-25 12:00:16 +00:00
export interface IErrorFunction {
2017-03-04 12:50:12 +00:00
(err): any
2016-09-25 12:00:16 +00:00
}
export interface ICustomEventFunction {
2017-03-04 12:50:12 +00:00
(): any
}
export interface ICustomEventObject {
2017-03-04 12:50:12 +00:00
eventName: string
eventFunction: ICustomEventFunction
}
/**
* class Smartstream handles
*/
2016-09-25 12:00:16 +00:00
export class Smartstream {
2017-03-04 12:50:12 +00:00
private streamArray = []
private customEventObjectArray: ICustomEventObject[] = []
private streamStartedDeferred = plugins.q.defer()
2016-09-25 14:28:42 +00:00
2017-03-04 12:50:12 +00:00
/**
* constructor
*/
constructor(streamArrayArg: any[]) {
this.streamArray = streamArrayArg
}
2017-03-04 12:50:12 +00:00
/**
* make something with the stream itself
*/
2017-06-30 16:32:32 +00:00
streamStarted (): Promise<any> {
2017-03-04 12:50:12 +00:00
return this.streamStartedDeferred.promise
}
2017-03-04 12:50:12 +00:00
/**
* attach listener to custom event
*/
2017-06-30 16:32:32 +00:00
onCustomEvent (eventNameArg: string, eventFunctionArg: ICustomEventFunction) {
2017-03-04 12:50:12 +00:00
this.customEventObjectArray.push({
eventName: eventNameArg,
eventFunction: eventFunctionArg
})
}
/**
* run the stream
* @returns Promise
*/
2017-06-30 16:32:32 +00:00
run (): Promise<void> {
2017-03-04 12:50:12 +00:00
let done = plugins.q.defer<void>()
2017-03-04 12:50:12 +00:00
// clone Array
let streamExecutionArray = []
for (let streamItem of this.streamArray) { streamExecutionArray.push(streamItem) }
2017-03-04 12:50:12 +00:00
// combine the stream
let finalStream = null
let firstIteration: boolean = true
for (let stream of streamExecutionArray) {
if (firstIteration === true) {
finalStream = stream
}
stream.on('error', (err) => {
done.reject(err)
})
for (let customEventObject of this.customEventObjectArray) {
stream.on(customEventObject.eventName, customEventObject.eventFunction)
}
if (!firstIteration) {
finalStream = finalStream.pipe(stream)
}
firstIteration = false
}
this.streamStartedDeferred.resolve()
2017-03-04 12:50:12 +00:00
finalStream.on('end', function () {
done.resolve()
})
finalStream.on('close', function () {
done.resolve()
})
finalStream.on('finish', function () {
done.resolve()
})
return done.promise
}
}
2016-09-25 14:28:42 +00:00
2017-03-04 12:50:12 +00:00
export let cleanPipe = () => {
2017-03-04 13:26:10 +00:00
return plugins.through2.obj(
2017-03-04 12:50:12 +00:00
(file, enc, cb) => {
cb()
},
(cb) => {
cb()
2016-09-25 12:00:16 +00:00
}
2017-03-04 12:50:12 +00:00
)
}