-
Notifications
You must be signed in to change notification settings - Fork 28
/
interceptor.go
34 lines (29 loc) · 1.12 KB
/
interceptor.go
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
package sqlingo
import (
"context"
)
// InvokerFunc is the function type of the actual invoker. It should be called in an interceptor.
type InvokerFunc = func(ctx context.Context, sql string) error
// InterceptorFunc is the function type of an interceptor. An interceptor should implement this function to fulfill it's purpose.
type InterceptorFunc = func(ctx context.Context, sql string, invoker InvokerFunc) error
func noopInterceptor(ctx context.Context, sql string, invoker InvokerFunc) error {
return invoker(ctx, sql)
}
// ChainInterceptors chains multiple interceptors into one interceptor.
func ChainInterceptors(interceptors ...InterceptorFunc) InterceptorFunc {
if len(interceptors) == 0 {
return noopInterceptor
}
return func(ctx context.Context, sql string, invoker InvokerFunc) error {
var chain func(int, context.Context, string) error
chain = func(i int, ctx context.Context, sql string) error {
if i == len(interceptors) {
return invoker(ctx, sql)
}
return interceptors[i](ctx, sql, func(ctx context.Context, sql string) error {
return chain(i+1, ctx, sql)
})
}
return chain(0, ctx, sql)
}
}