From dbf1373e0cdab891f7fbb9b206e20dd7e8aa3de1 Mon Sep 17 00:00:00 2001 From: Hayden <64056131+hay-kot@users.noreply.github.com> Date: Fri, 5 Jan 2024 11:12:33 -0600 Subject: [PATCH] basic currency service for loading at runtime --- .../internal/core/currencies/currencies.go | 87 +++++++++++++++++++ .../internal/core/currencies/currencies.json | 1 + 2 files changed, 88 insertions(+) create mode 100644 backend/internal/core/currencies/currencies.go create mode 100644 backend/internal/core/currencies/currencies.json diff --git a/backend/internal/core/currencies/currencies.go b/backend/internal/core/currencies/currencies.go new file mode 100644 index 0000000..fa255ca --- /dev/null +++ b/backend/internal/core/currencies/currencies.go @@ -0,0 +1,87 @@ +// Package currencies provides a shared definition of currencies. This uses a global +// variable to hold the currencies. +package currencies + +import ( + "bytes" + _ "embed" + "encoding/json" + "io" + "sync" +) + +//go:embed currencies.json +var defaults []byte + +type CollectorFunc func() ([]Currency, error) + +func CollectJSON(reader io.Reader) CollectorFunc { + return func() ([]Currency, error) { + var currencies []Currency + err := json.NewDecoder(reader).Decode(¤cies) + if err != nil { + return nil, err + } + + return currencies, nil + } +} + +func CollectDefaults() CollectorFunc { + return CollectJSON(bytes.NewReader(defaults)) +} + +func CollectionCurrencies(collectors ...CollectorFunc) ([]Currency, error) { + out := make([]Currency, 0, len(collectors)) + for i := range collectors { + c, err := collectors[i]() + if err != nil { + return nil, err + } + + out = append(out, c...) + } + + return out, nil +} + +type Currency struct { + Name string `json:"name"` + Code string `json:"code"` + Local string `json:"local"` + Symbol string `json:"symbol"` +} + +type CurrencyRegistry struct { + mu sync.RWMutex + registry map[string]Currency +} + +func NewCurrencyService(currencies []Currency) *CurrencyRegistry { + registry := make(map[string]Currency, len(currencies)) + for i := range currencies { + registry[currencies[i].Code] = currencies[i] + } + + return &CurrencyRegistry{ + registry: registry, + } +} + +func (cs *CurrencyRegistry) GetCurrencies() []Currency { + cs.mu.RLock() + defer cs.mu.RUnlock() + out := make([]Currency, 0, len(cs.registry)) + for key := range cs.registry { + out = append(out, cs.registry[key]) + } + + return out +} + +func (cs *CurrencyRegistry) IsSupported(code string) bool { + cs.mu.RLock() + defer cs.mu.RUnlock() + _, ok := cs.registry[code] + return ok +} diff --git a/backend/internal/core/currencies/currencies.json b/backend/internal/core/currencies/currencies.json new file mode 100644 index 0000000..fe51488 --- /dev/null +++ b/backend/internal/core/currencies/currencies.json @@ -0,0 +1 @@ +[]