Skip to content

Commit

Permalink
feat(interceptor): wrap() - single interceptor
Browse files Browse the repository at this point in the history
  • Loading branch information
chuan6 committed Aug 13, 2018
1 parent 32ab8bb commit 9ffa253
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 2 deletions.
4 changes: 2 additions & 2 deletions src/utils/interceptor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ type Gate<T, U extends any[]> = (...args: U) => Observable<T>

export function wrap<T, U extends any[]>(
gate: Gate<T, U>,
_interceptor?: any
interceptor: any = (_0: any, g: Gate<T, U>, args: U) => g(...args)
): (options?: {}) => (...args: U) => Observable<T> {
return () => gate
return (options: {} = {}) => (...args: U) => interceptor(options, gate, args)
}
62 changes: 62 additions & 0 deletions test/utils/interceptor.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,66 @@ describe.only('interceptor spec', () => {
expect(x).to.equal(3)
})
})

it('wrap: single interceptor for request', function* () {
const interceptor = (options: { checkDividedByZero: boolean }, gateFn: any, gateArgs: any[]) => {
if (options.checkDividedByZero) {
const divisor = gateArgs[1]
if (divisor === 0) {
return Observable.of(0)
}
}
return gateFn(...gateArgs)
}
const gate = (x: number, y: number) => Observable.of(x / y)
const wrapped = ix.wrap(gate, interceptor)
const intercepted = wrapped({ checkDividedByZero: true })
yield intercepted(1, 0)
.do((x) => {
expect(x).to.equal(0)
})
})

it('wrap: single interceptor for response', function* () {
const interceptor = (options: { catchError: boolean }, gateFn: any, gateArgs: any[]) => {
if (options.catchError) {
return gateFn(...gateArgs).catch((err: any) => Observable.of(err.message))
}
return gateFn(...gateArgs)
}
const gate = () => Observable.throw(new Error('hello'))
const wrapped = ix.wrap(gate, interceptor)
const intercepted = wrapped({ catchError: true })
yield intercepted()
.do((x) => {
expect(x).to.equal('hello')
})
})

it('wrap: single interceptor for both request and response', function* () {
const interceptor = (options: { checkDividedByZero: boolean, catchError: boolean }, gateFn: any, gateArgs: any[]) => {
let result: Observable<any>
if (options.checkDividedByZero) {
const divisor = gateArgs[1]
if (divisor === 0) {
result = Observable.throw(new Error('divided-by-zero'))
} else {
result = gateFn(...gateArgs)
}
} else {
result = gateFn(...gateArgs)
}
if (options.catchError) {
result = result.catch((err: any) => Observable.of(err.message))
}
return result
}
const gate = (x: number, y: number) => Observable.of(x / y)
const wrapped = ix.wrap(gate, interceptor)
const intercepted = wrapped({ checkDividedByZero: true, catchError: true })
yield intercepted(1, 0)
.do((x) => {
expect(x).to.equal('divided-by-zero')
})
})
})

0 comments on commit 9ffa253

Please sign in to comment.