mirror of https://github.com/lqs/sqlingo
add ChainInterceptors
This commit is contained in:
parent
2512270cf6
commit
65c4cf7d2d
|
|
@ -10,4 +10,25 @@ 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
|
||||
|
||||
// TODO: add some common interceptors
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,55 @@
|
|||
package sqlingo
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestChainInterceptors(t *testing.T) {
|
||||
s := ""
|
||||
i1 := func(ctx context.Context, sql string, invoker InvokerFunc) error {
|
||||
s += "<i1>"
|
||||
s += sql
|
||||
defer func() {
|
||||
s += "</i1>"
|
||||
}()
|
||||
return invoker(ctx, sql+"s1")
|
||||
}
|
||||
i2 := func(ctx context.Context, sql string, invoker InvokerFunc) error {
|
||||
s += "<i2>"
|
||||
s += sql
|
||||
defer func() {
|
||||
s += "</i2>"
|
||||
}()
|
||||
return invoker(ctx, sql+"s2")
|
||||
}
|
||||
chain := ChainInterceptors(i1, i2)
|
||||
_ = chain(context.Background(), "sql", func(ctx context.Context, sql string) error {
|
||||
s += "<invoker>"
|
||||
s += sql
|
||||
defer func() {
|
||||
s += "</invoker>"
|
||||
}()
|
||||
return nil
|
||||
})
|
||||
if s != "<i1>sql<i2>sqls1<invoker>sqls1s2</invoker></i2></i1>" {
|
||||
t.Error(s)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmptyChainInterceptors(t *testing.T) {
|
||||
s := ""
|
||||
chain := ChainInterceptors()
|
||||
_ = chain(context.Background(), "sql", func(ctx context.Context, sql string) error {
|
||||
s += "<invoker>"
|
||||
defer func() {
|
||||
s += "</invoker>"
|
||||
}()
|
||||
s += sql
|
||||
return nil
|
||||
})
|
||||
|
||||
if s != "<invoker>sql</invoker>" {
|
||||
t.Error(s)
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue