github.com/machinefi/w3bstream@v1.6.5-rc9.0.20240426031326-b8c7c4876e72/pkg/depends/kit/httptransport/req_tsfm_factory.go (about)

     1  package httptransport
     2  
     3  import (
     4  	"context"
     5  	"net/http"
     6  	"reflect"
     7  	"sync"
     8  
     9  	"github.com/machinefi/w3bstream/pkg/depends/kit/httptransport/transformer"
    10  	"github.com/machinefi/w3bstream/pkg/depends/kit/validator"
    11  	"github.com/machinefi/w3bstream/pkg/depends/x/reflectx"
    12  	"github.com/machinefi/w3bstream/pkg/depends/x/typesx"
    13  )
    14  
    15  type RequestTsfmFactory struct {
    16  	Vldt  validator.Factory
    17  	Tsfm  transformer.Factory
    18  	cache sync.Map
    19  }
    20  
    21  func NewRequestTsfmFactory(tsfm transformer.Factory, vldt validator.Factory) *RequestTsfmFactory {
    22  	r := &RequestTsfmFactory{Vldt: vldt, Tsfm: tsfm}
    23  	r.SetDefault()
    24  	return r
    25  }
    26  
    27  func (f *RequestTsfmFactory) SetDefault() {
    28  	if f.Vldt == nil {
    29  		f.Vldt = validator.DefaultFactory
    30  	}
    31  	if f.Tsfm == nil {
    32  		f.Tsfm = transformer.DefaultFactory
    33  	}
    34  }
    35  
    36  func (f *RequestTsfmFactory) NewRequest(method, url string, v interface{}) (*http.Request, error) {
    37  	return f.NewRequestWithContext(context.Background(), method, url, v)
    38  }
    39  
    40  func (f *RequestTsfmFactory) NewRequestWithContext(ctx context.Context, method, url string, v interface{}) (*http.Request, error) {
    41  	if v == nil {
    42  		return http.NewRequestWithContext(ctx, method, url, nil)
    43  	}
    44  	rt, err := f.NewRequestTsfm(AsRequestOut(ctx), reflect.TypeOf(v))
    45  	if err != nil {
    46  		return nil, err
    47  	}
    48  	return rt.NewReqWithContext(ctx, method, url, v)
    49  }
    50  
    51  func (f *RequestTsfmFactory) NewRequestTsfm(ctx context.Context, typ reflect.Type) (*RequestTsfm, error) {
    52  	if v, ok := f.cache.Load(typ); ok {
    53  		return v.(*RequestTsfm), nil
    54  	}
    55  	t, err := f.new(ctx, typ)
    56  	if err != nil {
    57  		return nil, err
    58  	}
    59  	f.cache.Store(typ, t)
    60  	return t, nil
    61  }
    62  
    63  func (f *RequestTsfmFactory) new(ctx context.Context, typ reflect.Type) (*RequestTsfm, error) {
    64  	rt := &RequestTsfm{}
    65  
    66  	rt.Params = map[string][]transformer.ReqParam{}
    67  	rt.Type = reflectx.DeRef(typ)
    68  
    69  	ctx = transformer.ContextWithFactory(ctx, f.Tsfm)
    70  	ctx = validator.ContextWithFactory(ctx, f.Vldt)
    71  
    72  	err := transformer.EachReqParam(
    73  		ctx, typesx.FromReflectType(rt.Type),
    74  		func(rp *transformer.ReqParam) {
    75  			if rp.In == "" {
    76  				return
    77  			}
    78  			rt.Params[rp.In] = append(rt.Params[rp.In], *rp)
    79  		},
    80  	)
    81  
    82  	return rt, err
    83  }