github.com/blend/go-sdk@v1.20220411.3/validate/map.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 validate
     9  
    10  import (
    11  	"reflect"
    12  
    13  	"github.com/blend/go-sdk/ex"
    14  	"github.com/blend/go-sdk/reflectutil"
    15  )
    16  
    17  // Errors
    18  const (
    19  	ErrInstanceNotMap ex.Class = "validated reference is not a map"
    20  	ErrMapKeys        ex.Class = "map should have keys"
    21  )
    22  
    23  // Map returns validators for a map type reference.
    24  func Map(instance interface{}) MapValidators {
    25  	return MapValidators{instance}
    26  }
    27  
    28  // MapValidators is a set of validators for maps.
    29  type MapValidators struct {
    30  	Value interface{}
    31  }
    32  
    33  // Keys validates a map contains a given set of keys.
    34  func (mv MapValidators) Keys(keys ...interface{}) Validator {
    35  	return func() error {
    36  		value := reflectutil.Value(mv.Value)
    37  		if value.Kind() != reflect.Map {
    38  			return ErrInstanceNotMap
    39  		}
    40  
    41  		for _, key := range keys {
    42  			mapValue := value.MapIndex(reflect.ValueOf(key))
    43  			if !mapValue.IsValid() {
    44  				return Errorf(ErrMapKeys, mv.Value, "missing key: %v", key)
    45  			}
    46  		}
    47  		return nil
    48  	}
    49  }