2024-08-06 12:10:25 +00:00
|
|
|
package models
|
|
|
|
|
|
|
|
import (
|
2024-08-06 19:35:28 +00:00
|
|
|
"context"
|
2024-08-06 12:10:25 +00:00
|
|
|
"database/sql"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
// DBModel is the type for database connection values
|
|
|
|
type DBModel struct {
|
|
|
|
DB *sql.DB
|
|
|
|
}
|
|
|
|
|
|
|
|
// Models is the wrapper for all models
|
|
|
|
type Models struct {
|
|
|
|
DB DBModel
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewModels returns a model type with database connection pool
|
|
|
|
func NewModels(db *sql.DB) Models {
|
|
|
|
return Models{
|
|
|
|
DB: DBModel{DB: db},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Widget is the type for all widgets
|
|
|
|
type Widget struct {
|
|
|
|
ID int `json:"id"`
|
|
|
|
Name string `json:"name"`
|
|
|
|
Description string `json:"description"`
|
|
|
|
InventoryLevel int `json:"inventory_level"`
|
|
|
|
Price int `json:"price"`
|
|
|
|
CreatedAt time.Time `json:"-"`
|
|
|
|
UpdatedAt time.Time `json:"-"`
|
|
|
|
}
|
2024-08-06 19:35:28 +00:00
|
|
|
|
|
|
|
func (m *DBModel) GetWidget(id int) (Widget, error) {
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
|
|
|
defer cancel()
|
|
|
|
|
|
|
|
var widget Widget
|
|
|
|
|
|
|
|
query := `SELECT id, name FROM widgets WHERE id = ?`
|
|
|
|
|
|
|
|
row := m.DB.QueryRowContext(ctx, query, id)
|
|
|
|
err := row.Scan(&widget.ID, &widget.Name)
|
|
|
|
if err != nil {
|
|
|
|
return widget, err
|
|
|
|
}
|
|
|
|
return widget, nil
|
|
|
|
}
|