price.go 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package pricing
  2. import (
  3. "errors"
  4. "github.com/opencost/opencost/core/pkg/unit"
  5. )
  6. var NotFound = errors.New("Not found")
  7. type Price struct {
  8. Currency unit.Currency `json:"currency" yaml:"currency"`
  9. Unit unit.Unit `json:"unit" yaml:"unit"`
  10. Price float64 `json:"price" yaml:"price"`
  11. }
  12. type Prices map[unit.Currency][]Price
  13. func (p Prices) GetPrices() []Price {
  14. prices := make([]Price, 0, len(p))
  15. for _, price := range p {
  16. prices = append(prices, price...)
  17. }
  18. return prices
  19. }
  20. func (p Prices) GetPricesInCurrency(currency unit.Currency) ([]Price, error) {
  21. result := []Price{}
  22. for curr, prices := range p {
  23. if curr == currency {
  24. result = append(result, prices...)
  25. }
  26. }
  27. if len(result) == 0 {
  28. return nil, NotFound
  29. }
  30. return result, nil
  31. }
  32. func (p Prices) GetPricesInCurrencyWithDefault(currency, defaultCurrency unit.Currency) ([]Price, error) {
  33. prices, err := p.GetPricesInCurrency(currency)
  34. if len(prices) > 0 && err == nil {
  35. return prices, nil
  36. }
  37. return p.GetPricesInCurrency(defaultCurrency)
  38. }