This repository has been archived by the owner on Mar 7, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
exchange-rates-handler.go
71 lines (53 loc) · 1.82 KB
/
exchange-rates-handler.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package plugin
import (
"net/http"
"github.com/go-chi/chi"
"github.com/go-chi/render"
"github.com/leonardochaia/vendopunkto/dtos"
"github.com/leonardochaia/vendopunkto/errors"
)
// ExchangeRatesHandler exposes the plugin through HTTP
type ExchangeRatesHandler struct {
plugin ExchangeRatesPlugin
serverPlugin ServerPlugin
}
type GetExchangeRatesParams struct {
Currency string `json:"currency"`
Currencies []string `json:"currencies"`
}
func NewExchangeRatesHandler(plugin ExchangeRatesPlugin, serverPlugin ServerPlugin) *chi.Mux {
router := chi.NewRouter()
handler := &ExchangeRatesHandler{
plugin: plugin,
serverPlugin: serverPlugin,
}
router.Post("/", errors.WrapHandler(handler.getExchangeRates))
router.Post(ExchangeRatesSupportedCurrencies, errors.WrapHandler(handler.searchSupportedCurrencies))
return router
}
func (handler *ExchangeRatesHandler) getExchangeRates(w http.ResponseWriter, r *http.Request) error {
const op errors.Op = "plugin.api.getExchangeRates"
var params = new(GetExchangeRatesParams)
if err := render.DecodeJSON(r.Body, ¶ms); err != nil {
return errors.E(op, errors.Parameters, err)
}
res, err := handler.plugin.GetExchangeRates(params.Currency, params.Currencies)
if err != nil {
return errors.E(op, errors.Internal, err)
}
render.JSON(w, r, res)
return nil
}
func (handler *ExchangeRatesHandler) searchSupportedCurrencies(w http.ResponseWriter, r *http.Request) error {
const op errors.Op = "plugin.api.searchSupportedCurrencies"
var params = new(dtos.SearchSupportedCurrenciesParams)
if err := render.DecodeJSON(r.Body, ¶ms); err != nil {
return errors.E(op, errors.Parameters, err)
}
res, err := handler.plugin.SearchSupportedCurrencies(params.Term)
if err != nil {
return errors.E(op, errors.Internal, err)
}
render.JSON(w, r, res)
return nil
}