-
Notifications
You must be signed in to change notification settings - Fork 1
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
base: dev2
Are you sure you want to change the base?
DB2 #4
Conversation
|
||
func (db *EventDB) DeleteEvent(ctx context.Context, ID int) error { | ||
_, err := db.pool.Exec(ctx, deleteEventQuery, ID) | ||
return err |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
На удаление, добавление и обновление сущностей в базе нужна обработка ошибок. Чтобы кидать 500 только в случае, когда действительно база упала
return port | ||
conf.Port = port | ||
|
||
redisConfig, err := sessionRepository.GetRedisConfig() |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Странно выходит, что конфиг импортирует модули репозитория. По идее должно быть наоборот
internal/service/events/event.go
Outdated
event, err := s.EventDB.AddEvent(ctx, event) | ||
if err != nil { | ||
if path != "" { | ||
s.ImageDB.DeleteImage(ctx, path) |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Забыли условие на число поставить
subscriber_id INT NOT NULL, | ||
subscribed_id INT NOT NULL, |
There was a problem hiding this comment.
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) { |
There was a problem hiding this comment.
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 || '%') |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
ILIKE нормально не работает с индексами, почитайте доку постгреса. Лучше делать lower() с обычным LIKE
var pgErr *pgconn.PgError | ||
if errors.As(err, &pgErr) { | ||
return models.ErrForeignKeyViolation | ||
} |
There was a problem hiding this comment.
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", |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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, |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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")) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Когда появится нормальная обработка кодов ошибок постгреса, надо будет возвращать здесь ошибки pgx. Также, где уместно, добавить проверки на sql.ErrNoRows
No description provided.