Newer
Older
pokemon-go-trade / internal / db / db.go
package db

import (
	"github.com/jmoiron/sqlx"
	"github.com/pkg/errors"
)

type Package struct {
	Db *sqlx.DB
}

type Interface interface {
	GetPokemons() ([]Pokemon, error)
	StoreHavePokemons(havePokemons []HavePokemon) error
	GetHavePokemons() ([]Pokemon, error)
}

type Pokemon struct {
	ID             int    `db:"id"`
	DexNumber      int    `db:"dex_number"`
	Region         string `db:"region"`
	Name           string `db:"name"`
	ShinyEnabled   bool   `db:"shiny_enabled"`
	ShinyImageName string `db:"shiny_image_name"`
	ImageName      string `db:"image_name"`
}

type HavePokemon struct {
	ID        int  `db:"id"`
	PokemonID int  `db:"pokemon_id"`
	Shiny     bool `db:"shiny"`
}

func (p *Package) GetPokemons() ([]Pokemon, error) {
	var pokemons []Pokemon
	err := p.Db.Select(&pokemons, "SELECT * FROM pokemon")
	if err != nil {
		return nil, errors.WithStack(err)
	}
	return pokemons, nil
}

func (p *Package) GetHavePokemons() ([]Pokemon, error) {
	var pokemons []Pokemon
	err := p.Db.Select(&pokemons, "SELECT pokemon.id, pokemon.dex_number, pokemon.region, "+
		"have_pokemon.shiny as shiny_enabled, pokemon.name, pokemon.shiny_image_name, pokemon.image_name "+
		"FROM pokemon JOIN have_pokemon ON have_pokemon.pokemon_id = pokemon.id")
	if err != nil {
		return nil, errors.WithStack(err)
	}
	return pokemons, nil
}

func (p *Package) StoreHavePokemons(havePokemons []HavePokemon) error {
	insertQuery := `INSERT INTO have_pokemon (pokemon_id, shiny) VALUES (:pokemon_id, :shiny)`
	for _, havePokemon := range havePokemons {
		_, err := p.Db.NamedExec(insertQuery, havePokemon)
		if err != nil {
			return errors.WithStack(err)
		}
	}
	return nil
}