github.com/blend/go-sdk@v1.20220411.3/grpcutil/unary_server_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 grpcutil
     9  
    10  import (
    11  	"context"
    12  
    13  	"google.golang.org/grpc"
    14  )
    15  
    16  // UnaryServerChain reads the middleware variadic args and organizes the calls recursively in the order they appear.
    17  func UnaryServerChain(interceptors ...grpc.UnaryServerInterceptor) grpc.UnaryServerInterceptor {
    18  	// if we don't have interceptors, return a no-op.
    19  	if len(interceptors) == 0 {
    20  		return func(ctx context.Context, req interface{}, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
    21  			return handler(ctx, req)
    22  		}
    23  	}
    24  	// if we only have one interceptor, return it
    25  	if len(interceptors) == 1 {
    26  		return interceptors[0]
    27  	}
    28  
    29  	// nest the interceptors
    30  	var nest = func(a, b grpc.UnaryServerInterceptor) grpc.UnaryServerInterceptor {
    31  		if b == nil {
    32  			return a
    33  		}
    34  		return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
    35  			curried := func(ictx context.Context, ireq interface{}) (interface{}, error) {
    36  				return b(ictx, ireq, info, handler)
    37  			}
    38  			return a(ctx, req, info, curried)
    39  		}
    40  	}
    41  
    42  	var outer grpc.UnaryServerInterceptor
    43  	for _, step := range interceptors {
    44  		outer = nest(step, outer)
    45  	}
    46  	return outer
    47  }