github.com/altipla-consulting/ravendb-go-client@v0.1.3/multi_loader_with_include.go (about)

     1  package ravendb
     2  
     3  import (
     4  	"reflect"
     5  )
     6  
     7  // ILoaderWithInclude is NewMultiLoaderWithInclude
     8  
     9  type MultiLoaderWithInclude struct {
    10  	session  *DocumentSession
    11  	includes []string
    12  }
    13  
    14  func NewMultiLoaderWithInclude(session *DocumentSession) *MultiLoaderWithInclude {
    15  	return &MultiLoaderWithInclude{
    16  		session: session,
    17  	}
    18  }
    19  
    20  func (l *MultiLoaderWithInclude) Include(path string) *MultiLoaderWithInclude {
    21  	l.includes = append(l.includes, path)
    22  	return l
    23  }
    24  
    25  // results should be map[string]*struct
    26  func (l *MultiLoaderWithInclude) LoadMulti(results interface{}, ids []string) error {
    27  	if len(ids) == 0 {
    28  		return newIllegalArgumentError("ids cannot be empty array")
    29  	}
    30  	if err := checkValidLoadMultiArg(results, "results"); err != nil {
    31  		return err
    32  	}
    33  
    34  	return l.session.loadInternalMulti(results, ids, l.includes)
    35  }
    36  
    37  // TODO: needs a test
    38  // TODO: better implementation
    39  func (l *MultiLoaderWithInclude) Load(result interface{}, id string) error {
    40  	if id == "" {
    41  		return newIllegalArgumentError("id cannot be empty string")
    42  	}
    43  	// TODO: should allow map[string]interface{} as argument? (and therefore use checkValidLoadArg)
    44  	if err := checkIsPtrPtrStruct(result, "result"); err != nil {
    45  		return err
    46  	}
    47  
    48  	// create a map[string]typeof(result)
    49  	rt := reflect.TypeOf(result)
    50  	rt = rt.Elem() // it's now ptr-to-struct
    51  
    52  	mapType := reflect.MapOf(stringType, rt)
    53  	m := reflect.MakeMap(mapType)
    54  	ids := []string{id}
    55  	err := l.session.loadInternalMulti(m.Interface(), ids, l.includes)
    56  	if err != nil {
    57  		return err
    58  	}
    59  	key := reflect.ValueOf(id)
    60  	res := m.MapIndex(key)
    61  	if res.IsNil() {
    62  		//return ErrNotFound
    63  		return nil
    64  	}
    65  	return setInterfaceToValue(result, res.Interface())
    66  }