Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

DB2 #4

Open
wants to merge 37 commits into
base: dev2
Choose a base branch
from
Open

DB2 #4

wants to merge 37 commits into from

Conversation

Achpochmak
Copy link
Collaborator

No description provided.

Makefile Outdated Show resolved Hide resolved
docs/docs.go Outdated Show resolved Hide resolved
internal/db/connection.go Outdated Show resolved Hide resolved
internal/db/connection.go Outdated Show resolved Hide resolved
internal/db/connection.go Outdated Show resolved Hide resolved
internal/repository/events/events.go Outdated Show resolved Hide resolved
internal/repository/events/events.go Outdated Show resolved Hide resolved
migrations/00003_create_trigger_event_update.sql Outdated Show resolved Hide resolved
migrations/00004_init_category_values.sql Outdated Show resolved Hide resolved
internal/repository/events/events.go Outdated Show resolved Hide resolved
cmd/server/main.go Outdated Show resolved Hide resolved
internal/http/auth/auth.go Outdated Show resolved Hide resolved
internal/http/auth/auth.go Outdated Show resolved Hide resolved
cmd/server/main.go Outdated Show resolved Hide resolved
internal/http/events/events.go Outdated Show resolved Hide resolved
internal/repository/postgres/events/events.go Outdated Show resolved Hide resolved

func (db *EventDB) DeleteEvent(ctx context.Context, ID int) error {
_, err := db.pool.Exec(ctx, deleteEventQuery, ID)
return err
Copy link
Collaborator

Choose a reason for hiding this comment

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

На удаление, добавление и обновление сущностей в базе нужна обработка ошибок. Чтобы кидать 500 только в случае, когда действительно база упала

internal/repository/postgres/events/events.go Outdated Show resolved Hide resolved
internal/repository/postgres/events/events.go Outdated Show resolved Hide resolved
internal/repository/postgres/events/events.go Outdated Show resolved Hide resolved
cmd/server/main.go Outdated Show resolved Hide resolved
cmd/server/main.go Outdated Show resolved Hide resolved
return port
conf.Port = port

redisConfig, err := sessionRepository.GetRedisConfig()
Copy link
Collaborator

Choose a reason for hiding this comment

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

Странно выходит, что конфиг импортирует модули репозитория. По идее должно быть наоборот

internal/http/auth/auth.go Outdated Show resolved Hide resolved
internal/http/auth/auth.go Outdated Show resolved Hide resolved
internal/repository/images/image.go Outdated Show resolved Hide resolved
internal/service/auth/auth.go Show resolved Hide resolved
internal/http/events/events.go Outdated Show resolved Hide resolved
internal/service/events/event.go Outdated Show resolved Hide resolved
event, err := s.EventDB.AddEvent(ctx, event)
if err != nil {
if path != "" {
s.ImageDB.DeleteImage(ctx, path)
Copy link
Collaborator

Choose a reason for hiding this comment

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

Надо залогировать ошибку. Я бы для этого прокинул логгер через контекст

r.HandleFunc("/logout", authHandler.Logout).Methods(http.MethodPost)
r.HandleFunc("/session", authHandler.CheckSession).Methods(http.MethodGet)

r.HandleFunc("/profile/{id}", authHandler.Profile).Methods(http.MethodGet)
Copy link
Collaborator

Choose a reason for hiding this comment

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

Забыли условие на число поставить

Comment on lines +5 to +6
subscriber_id INT NOT NULL,
subscribed_id INT NOT NULL,
Copy link
Collaborator

Choose a reason for hiding this comment

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

Я бы задумался о переименовании этих полей, как будто легко запутаться

VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
RETURNING id`

func (db *EventDB) AddEvent(ctx context.Context, event models.Event) (models.Event, error) {
Copy link
Collaborator

Choose a reason for hiding this comment

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

Имхо лучше Create, чем Add, мне кажется интуитивнее (но это имхо, можете оставить)

LEFT JOIN tag ON tag.id = event_tag.tag_id
LEFT JOIN media_url ON event.id = media_url.event_id
WHERE
($1::TEXT IS NULL OR event.title ILIKE '%' || $1 || '%' OR event.description ILIKE '%' || $1 || '%')
Copy link
Collaborator

Choose a reason for hiding this comment

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

ILIKE нормально не работает с индексами, почитайте доку постгреса. Лучше делать lower() с обычным LIKE

Comment on lines +21 to +24
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) {
return models.ErrForeignKeyViolation
}
Copy link
Collaborator

Choose a reason for hiding this comment

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

Надо проверять на код конкретной ошибки постгреса

@@ -14,6 +14,9 @@ func CORSMiddleware(next http.Handler) http.Handler {
"http://37.139.40.252",
"http://37.139.40.252:8080",
"37.139.40.252",
"127.0.0.1:8080",
Copy link
Collaborator

@reddiridabl666 reddiridabl666 Nov 16, 2024

Choose a reason for hiding this comment

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

Голые айпи я бы отсюда убрал, как я понимаю, origin всегда включает в себя протокол

uploadPath = "./static/images"
defaultPage = 0
defaultLimit = 30
maxUploadSize = 1 * 1024 * 1024 // 1Mb
Copy link
Collaborator

Choose a reason for hiding this comment

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

1 МБ может быть слишком маленьким значением. Также стоит задуматься над тем, чтобы выводить на фронте максимальный размер вложений (лучше перед загрузкой картинки, но нормальную ошибку с указанием макс размера тоже возвращать надо)

logger: logger,
}
},
wantCode: http.StatusInternalServerError,
Copy link
Collaborator

Choose a reason for hiding this comment

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

Мне кажется, лучше оперировать терминами expected/actual, чем want

recorder := httptest.NewRecorder()
tt.setupFunc(ctrl).GetUpcomingEvents(recorder, tt.req)

assert.Equal(t, tt.wantCode, recorder.Code)
Copy link
Collaborator

Choose a reason for hiding this comment

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

Кода недостаточно, нужно проверять и ответ. Либо парсить его в структуру и проверять на равенство с ожидаемой, либо JSONEqual

mockSetup: func(m pgxmock.PgxConnIface) {
m.ExpectExec(`DELETE FROM event WHERE id=\$1`).
WithArgs(3).
WillReturnError(fmt.Errorf("database error"))
Copy link
Collaborator

Choose a reason for hiding this comment

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

Когда появится нормальная обработка кодов ошибок постгреса, надо будет возвращать здесь ошибки pgx. Также, где уместно, добавить проверки на sql.ErrNoRows

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