github.com/blend/go-sdk@v1.20220411.3/db/statement_interceptor_chain.go (about) 1 /* 2 3 Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved 4 Use of this source code is governed by a MIT license that can be found in the LICENSE file. 5 6 */ 7 8 package db 9 10 import "context" 11 12 // StatementInterceptorChain nests interceptors such that a list of interceptors is 13 // returned as a single function. 14 // 15 // The nesting is such that if this function is provided arguments as `a, b, c` the returned 16 // function would be in the form `c(b(a(...)))` i.e. the functions would be run in left to right order. 17 func StatementInterceptorChain(interceptors ...StatementInterceptor) StatementInterceptor { 18 if len(interceptors) == 0 { 19 return func(ctx context.Context, label, statement string) (string, error) { 20 return statement, nil 21 } 22 } 23 if len(interceptors) == 1 { 24 return interceptors[0] 25 } 26 var nest = func(a, b StatementInterceptor) StatementInterceptor { 27 if a == nil { 28 return b 29 } 30 if b == nil { 31 return a 32 } 33 34 return func(ctx context.Context, label, statement string) (string, error) { 35 var err error 36 statement, err = b(ctx, label, statement) 37 if err != nil { 38 return statement, err 39 } 40 return a(ctx, label, statement) 41 } 42 } 43 44 var outer StatementInterceptor 45 for _, step := range interceptors { 46 outer = nest(step, outer) 47 } 48 return outer 49 }