gulp-function/ts/index.ts

90 lines
2.3 KiB
TypeScript
Raw Normal View History

import 'typings-global'
2017-04-29 22:44:11 +00:00
import * as q from 'smartq'
import * as through2 from 'through2'
import { Transform } from 'stream'
export type TExecutionMode = 'forEach' | 'forFirst' | 'atEnd'
export interface IPromiseFunction {
2017-04-29 22:44:11 +00:00
(file?, enc?): PromiseLike<any>
}
2016-10-19 05:36:32 +00:00
let defaultExport = (
2017-04-29 22:44:11 +00:00
functionsToExecuteArg: IPromiseFunction | IPromiseFunction[],
executionModeArg: TExecutionMode = 'forEach'
): Transform => {
2015-09-17 20:58:19 +00:00
2017-04-29 22:44:11 +00:00
let promiseArray = []
let runFunction = function (functionArg, file, enc) {
let returnValue = functionArg(file, enc)
if (typeof returnValue !== 'undefined' && typeof returnValue.then !== 'undefined') {
promiseArray.push(returnValue)
}
2017-04-29 22:44:11 +00:00
}
2015-09-17 20:58:19 +00:00
2017-04-29 22:44:11 +00:00
let checkAndRunFunction = function (file, enc) {
if (typeof functionsToExecuteArg === 'function') {
runFunction(functionsToExecuteArg, file, enc)
} else if (Array.isArray(functionsToExecuteArg)) {
for (let anyFunction in functionsToExecuteArg) {
runFunction(functionsToExecuteArg[ anyFunction ], file, enc)
}
} else {
throw new Error('gulp-callfunction: something is strange with the given arguments')
}
2017-04-29 22:44:11 +00:00
return Promise.all(promiseArray)
}
2015-10-25 21:45:49 +00:00
2017-04-29 22:44:11 +00:00
let hasExecutedOnce = false
let forEach = function (file, enc, cb) { // the forEach function is called for every chunk
switch (executionModeArg) {
case 'forEach':
checkAndRunFunction(file, enc).then(function () {
cb(null, file)
})
break
case 'forFirst':
if (hasExecutedOnce) {
checkAndRunFunction(file, enc)
.then(function () {
cb(null, file)
})
} else {
2017-04-29 22:44:11 +00:00
cb(null, file)
2015-11-30 08:49:52 +00:00
}
2017-04-29 22:44:11 +00:00
hasExecutedOnce = true
break
case 'atEnd':
2017-04-29 23:07:30 +00:00
cb()
2017-04-29 22:44:11 +00:00
break
default:
break
}
}
let atEnd = function (cb) {
if (executionModeArg === 'atEnd') {
checkAndRunFunction(null, null).then(function () {
cb()
})
} else {
cb()
}
2017-04-29 22:44:11 +00:00
}
return through2.obj(forEach, atEnd)
}
2016-10-18 23:10:45 +00:00
2016-10-19 05:36:32 +00:00
export let forEach = (funcArg: IPromiseFunction) => {
2017-04-29 22:44:11 +00:00
return defaultExport(funcArg, 'forEach')
2016-10-19 05:36:32 +00:00
}
export let forFirst = (funcArg: IPromiseFunction) => {
2017-04-29 22:44:11 +00:00
return defaultExport(funcArg, 'forFirst')
2016-10-19 05:36:32 +00:00
}
export let atEnd = (funcArg: IPromiseFunction) => {
2017-04-29 22:44:11 +00:00
return defaultExport(funcArg, 'atEnd')
2016-10-19 05:36:32 +00:00
}
export default defaultExport