moving handlers into service. adding website
This commit is contained in:
@@ -3,12 +3,51 @@ package service
|
||||
import (
|
||||
"Portifolio/internal/model"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
_ "github.com/mattn/go-sqlite3"
|
||||
)
|
||||
|
||||
func InsertCurrency(db *sql.DB, input model.CurrencyInput) (int, error) {
|
||||
res, err := db.Exec(
|
||||
type Service struct {
|
||||
db *sql.DB
|
||||
}
|
||||
|
||||
func (s *Service) AddCurrencyHandler() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
var input model.CurrencyInput
|
||||
if err := json.NewDecoder(r.Body).Decode(&input); err != nil {
|
||||
http.Error(w, "invalid json", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
id, err := s.InsertCurrency(input)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
json.NewEncoder(w).Encode(map[string]any{"status": "created", "id": id})
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) GetCurrenciesHandler() http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
currencies, err := s.GetAllCurrencies()
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(currencies)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) InsertCurrency(input model.CurrencyInput) (int, error) {
|
||||
res, err := s.db.Exec(
|
||||
`INSERT INTO currencies (code, name) VALUES (?, ?)`,
|
||||
input.Code, input.Name,
|
||||
)
|
||||
@@ -19,9 +58,9 @@ func InsertCurrency(db *sql.DB, input model.CurrencyInput) (int, error) {
|
||||
return int(id), err
|
||||
}
|
||||
|
||||
func GetCurrencyByCode(db *sql.DB, code string) (*model.Currency, error) {
|
||||
func (s *Service) GetCurrencyByCode(code string) (*model.Currency, error) {
|
||||
c := &model.Currency{}
|
||||
err := db.QueryRow(
|
||||
err := s.db.QueryRow(
|
||||
`SELECT id, code, name FROM currencies WHERE code = ?`, code,
|
||||
).Scan(&c.ID, &c.Code, &c.Name)
|
||||
if err == sql.ErrNoRows {
|
||||
@@ -30,8 +69,8 @@ func GetCurrencyByCode(db *sql.DB, code string) (*model.Currency, error) {
|
||||
return c, err
|
||||
}
|
||||
|
||||
func GetAllCurrencies(db *sql.DB) ([]model.Currency, error) {
|
||||
rows, err := db.Query(`SELECT id, code, name FROM currencies ORDER BY code`)
|
||||
func (s *Service) GetAllCurrencies() ([]model.Currency, error) {
|
||||
rows, err := s.db.Query(`SELECT id, code, name FROM currencies ORDER BY code`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user