github.com/prebid/prebid-server/v2@v2.18.0/adservertargeting/reqcache.go (about)

     1  package adservertargeting
     2  
     3  import (
     4  	"encoding/json"
     5  
     6  	"github.com/buger/jsonparser"
     7  	"github.com/prebid/openrtb/v20/openrtb2"
     8  	"github.com/prebid/prebid-server/v2/util/jsonutil"
     9  )
    10  
    11  type requestCache struct {
    12  	resolvedReq json.RawMessage
    13  	impsData    []json.RawMessage
    14  }
    15  
    16  func (reqImpCache *requestCache) GetReqJson() []byte {
    17  	return reqImpCache.resolvedReq
    18  }
    19  
    20  func (reqImpCache *requestCache) GetImpsData() ([]json.RawMessage, error) {
    21  	if len(reqImpCache.impsData) == 0 {
    22  		imps, _, _, err := jsonparser.Get(reqImpCache.resolvedReq, "imp")
    23  		if err != nil {
    24  			return nil, err
    25  		}
    26  		var impsData []json.RawMessage
    27  
    28  		err = jsonutil.Unmarshal(imps, &impsData)
    29  		if err != nil {
    30  			return nil, err
    31  		}
    32  		reqImpCache.impsData = impsData
    33  	}
    34  	return reqImpCache.impsData, nil
    35  }
    36  
    37  type bidsCache struct {
    38  	// bidder name is another layer to avoid collisions in case bid ids from different bidders will be the same
    39  	// map[bidder name] map [bid id] bid data
    40  	bids map[string]map[string][]byte
    41  }
    42  
    43  func (bidsCache *bidsCache) GetBid(bidderName, bidId string, bid openrtb2.Bid) ([]byte, error) {
    44  
    45  	_, seatBidExists := bidsCache.bids[bidderName]
    46  	if !seatBidExists {
    47  		impToBid := make(map[string][]byte, 0)
    48  		bidsCache.bids[bidderName] = impToBid
    49  	}
    50  	_, bidExists := bidsCache.bids[bidderName][bidId]
    51  	if !bidExists {
    52  		bidBytes, err := jsonutil.Marshal(bid)
    53  		if err != nil {
    54  			return nil, err
    55  		}
    56  		bidsCache.bids[bidderName][bidId] = bidBytes
    57  	}
    58  	return bidsCache.bids[bidderName][bidId], nil
    59  }