-
Notifications
You must be signed in to change notification settings - Fork 0
/
CircuitBreakerCallAdapter.ts
42 lines (35 loc) · 1.37 KB
/
CircuitBreakerCallAdapter.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import { CallAdapter } from '@drizzle-http/core'
import { Call } from '@drizzle-http/core'
import { HttpRequest } from '@drizzle-http/core'
import CircuitBreaker from 'opossum'
import { Registry } from './Registry'
interface CircuitBreakerInit {
options: CircuitBreaker.Options
registry: Registry
fallback?: (...args: unknown[]) => unknown
}
export class CircuitBreakerCallAdapter implements CallAdapter<unknown, unknown> {
private readonly options: CircuitBreaker.Options
private readonly registry: Registry
private readonly fallback?: (...args: unknown[]) => unknown
constructor(
init: CircuitBreakerInit,
private readonly decorated: CallAdapter<unknown, Promise<unknown>> | null = null
) {
this.options = init.options
this.registry = init.registry
this.fallback = init.fallback
}
adapt(action: Call<unknown>): (request: HttpRequest, argv: unknown[]) => Promise<unknown> {
const call = this.decorated?.adapt(action)
const circuitBreaker = new CircuitBreaker<[HttpRequest, unknown[]], unknown>(
(request, argv) => (call ? call(request, argv) : action.execute(request, argv)),
{ ...this.options }
)
if (this.fallback) {
circuitBreaker.fallback((...[_, argv, error]) => this.fallback?.(...argv, error))
}
this.registry.register(circuitBreaker)
return (request, argv) => circuitBreaker.fire(request, argv)
}
}