Skip to content

Conversation

@rLukoyanov
Copy link
Member

@rLukoyanov rLukoyanov commented Mar 18, 2025

Подключение PostgreSQL

В этом сервисе работаем без ОРМ/Билдеров и прочих вещей, прокачиваем навыки sql

  • Вынес данные бд в env
  • Добавил миграцию (liquidBase/Goose)

/equipments

GET - /equipments список всего инвентаря
GET - /equipments/:id получение инвентаря по айди
POST - /equipments создание инвентаря

{
    title: "title", // required
    image: "url"
}

PUT- /equipments/:id обновление инвентаря

{
    title: "title"
    image: "url"
}

DELETE - /equipments/:id удаление инвентаря

Деплой

@zeroT4lant
Copy link

Для миграций можно использовать liquidBase/Goose

Comment on lines 12 to 38
func InitPostgres() *sql.DB {
err := godotenv.Load()

if err != nil {
fmt.Println("Ошибка загрузки .env")
}

host := os.Getenv("HOST")
port := os.Getenv("PORT")
username := os.Getenv("POSTGRES_USERNAME")
password := os.Getenv("POSTGRES_PASSWORD")
databaseName := os.Getenv("DBNAME")

psqlInfo := fmt.Sprintf("host=%s port=%s user=%s "+
"password=%s dbname=%s sslmode=disable",
host, port, username, password, databaseName)

DB, err := sql.Open("postgres", psqlInfo)
if err != nil {
fmt.Println(err.Error())
panic("База данных нихуя не работает")
}

InitTables(DB)

return DB
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Добавить помимо функции инициализации структуру, чтобы все конфиги были в одном месте, желательно отдельную папку config/config.go

err := godotenv.Load()

if err != nil {
fmt.Println("Ошибка загрузки .env")

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

на работе в рот накажут

@rLukoyanov rLukoyanov requested a review from zeroT4lant March 20, 2025 23:24
@rLukoyanov rLukoyanov changed the title Add postgres connection Add postgres/equimpment CRUD Mar 20, 2025
@rLukoyanov rLukoyanov changed the title Add postgres/equimpment CRUD Add postgres & equimpment CRUD Mar 20, 2025
@rLukoyanov rLukoyanov changed the title Add postgres & equimpment CRUD Equimpment CRUD Mar 22, 2025
.env.example Outdated
@@ -0,0 +1,7 @@
HOST="localhost"
PORT=5432

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

хлопни

)

func InitPostgres(cfg *config.Config) *pgxpool.Pool {
ctx := context.Background()

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

контекст передавай в аргументе из главного main файла

"theaesthetics.ru/base/internal/services"
)

func InitRouter(e *echo.Echo, db *pgxpool.Pool) {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

желательно передавать в аргументе log из мейна

Comment on lines +27 to +29
return c.JSON(http.StatusInternalServerError, map[string]string{
"error": err.Error(),
})

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

функцию для оборачивания ошибки желательно

ctx := context.Background()
var equipment models.Equipment
err := c.Bind(&equipment)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

проверку на уникальность, есть ли в бд запись с таким именем

@@ -0,0 +1,151 @@
-- +goose Up

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

один большой блок для накатки и для откатки

}

func (r *EquipmentRepository) CreateEqipment(ctx context.Context, title, image string) error {
query := `INSERT INTO equipments (title, image) VALUES ($1, $2)`

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

транзакции добавить

return nil
}

func (r *EquipmentRepository) RemoveEquipment(ctx context.Context, id uint8) error {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

поменять на Delete желательно

}

func (r *EquipmentRepository) UpdateEquipment(ctx context.Context, equipment models.Equipment) error {
query := `UPDATE equipments SET title = $1, image = $2 WHERE id = $3`

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

транзкации добавить

e.Use(middleware.LoggerWithConfig(middleware.LoggerConfig{
Format: "method=${method}, uri=${uri}, status=${status}\n",
}))

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

будет круто добавить graceful shutdown

@rLukoyanov rLukoyanov merged commit d2ab960 into main Mar 23, 2025
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants