From 9a0cdfbccdbdafdb206524e44bebb4a0893f5ae4 Mon Sep 17 00:00:00 2001 From: litsynp Date: Sun, 22 Dec 2024 11:55:32 +0900 Subject: [PATCH] refactor: add error middleware --- .golangci.yml | 4 +- api/errors.go | 4 + api/web.go | 14 +- cmd/import_breeds/main.go | 2 +- cmd/import_conditions/main.go | 6 +- cmd/migrateuuids/main.go | 2 +- cmd/migrateuuids/uuidmigrator.go | 6 +- cmd/server/handler/auth_handler.go | 17 +- cmd/server/handler/breed_handler.go | 4 +- cmd/server/handler/chat_handler.go | 36 ++-- cmd/server/handler/condition_handler.go | 2 +- cmd/server/handler/media_handler.go | 22 +-- cmd/server/handler/sos_post_handler.go | 29 ++- cmd/server/handler/user_handler.go | 58 +++--- cmd/server/router.go | 21 +++ internal/common/null.go | 2 +- internal/datatype/uuid.go | 2 +- internal/infra/bucket/client.go | 4 +- internal/infra/database/transaction.go | 20 +- internal/service/auth_service.go | 18 +- internal/service/breed_service.go | 2 +- internal/service/chat_service.go | 27 +-- internal/service/media_service.go | 14 +- internal/service/sos_condition_service.go | 4 +- internal/service/sos_post_service.go | 173 +++++++++--------- .../service/tests/sos_post_service_test.go | 14 +- internal/service/tests/user_service_test.go | 12 +- internal/service/user_service.go | 70 +++---- internal/tests/service.go | 3 +- internal/wschat/server.go | 14 +- 30 files changed, 311 insertions(+), 295 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index b87cc056..274175e0 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -30,6 +30,8 @@ linters-settings: # Such cases aren't reported by default. # Default: false check-type-assertions: true + exclude-functions: + - (*github.com/pet-sitter/pets-next-door-api/internal/infra/database.Tx).Rollback exhaustive: # Program elements to check for exhaustiveness. @@ -490,7 +492,7 @@ linters: - nakedret # finds naked returns in functions greater than a specified function length - nestif # reports deeply nested if statements - nilerr # finds the code that returns nil even if it checks that the error is not nil - - nilnil # checks that there is no simultaneous return of nil error and an invalid value + # - nilnil # checks that there is no simultaneous return of nil error and an invalid value - noctx # finds sending http request without context.Context - nolintlint # reports ill-formed or insufficient nolint directives - nosprintfhostport # checks for misuse of Sprintf to construct a host with port in a URL diff --git a/api/errors.go b/api/errors.go index ede6f2cc..70bc931b 100644 --- a/api/errors.go +++ b/api/errors.go @@ -46,6 +46,10 @@ type AppError struct { Message string `json:"message,omitempty"` } +func (e *AppError) Error() string { + return e.Message +} + func NewAppError(err error, statusCode int, code AppErrorCode, message string) *AppError { log.Error().Err(err).Msg(message) return &AppError{ diff --git a/api/web.go b/api/web.go index 3c21bb68..93a6e9cd 100644 --- a/api/web.go +++ b/api/web.go @@ -11,7 +11,7 @@ import ( "github.com/labstack/echo/v4" ) -func ParseBody(c echo.Context, payload interface{}) *AppError { +func ParseBody(c echo.Context, payload interface{}) error { if err := c.Bind(payload); err != nil { return ErrInvalidBody(err) } @@ -22,7 +22,7 @@ func ParseBody(c echo.Context, payload interface{}) *AppError { return nil } -func ParseIDFromPath(c echo.Context, path string) (uuid.UUID, *AppError) { +func ParseIDFromPath(c echo.Context, path string) (uuid.UUID, error) { idStr := c.Param(path) id, err := uuid.Parse(idStr) if err != nil { @@ -32,7 +32,7 @@ func ParseIDFromPath(c echo.Context, path string) (uuid.UUID, *AppError) { return id, nil } -func ParseOptionalUUIDQuery(c echo.Context, query string) (uuid.NullUUID, *AppError) { +func ParseOptionalUUIDQuery(c echo.Context, query string) (uuid.NullUUID, error) { queryStr := c.QueryParam(query) if queryStr == "" { return uuid.NullUUID{}, nil @@ -48,7 +48,7 @@ func ParseOptionalUUIDQuery(c echo.Context, query string) (uuid.NullUUID, *AppEr return uuid.NullUUID{UUID: id, Valid: true}, nil } -func ParseOptionalIntQuery(c echo.Context, query string) (*int, *AppError) { +func ParseOptionalIntQuery(c echo.Context, query string) (*int, error) { queryStr := c.QueryParam(query) if queryStr == "" { return nil, nil @@ -62,7 +62,7 @@ func ParseOptionalIntQuery(c echo.Context, query string) (*int, *AppError) { return &value, nil } -func ParseRequiredStringQuery(c echo.Context, query string) (*string, *AppError) { +func ParseRequiredStringQuery(c echo.Context, query string) (*string, error) { queryStr := c.QueryParam(query) if queryStr == "" { return nil, ErrInvalidQuery(fmt.Errorf("expected non-empty string for query: %s", query)) @@ -84,7 +84,7 @@ func ParseOptionalStringQuery(c echo.Context, query string) *string { func ParsePaginationQueries( c echo.Context, defaultPage, defaultLimit int, -) (page, size int, err *AppError) { +) (page, size int, err error) { pageQuery := c.QueryParam("page") sizeQuery := c.QueryParam("size") @@ -116,7 +116,7 @@ func ParsePaginationQueries( func ParseCursorPaginationQueries( c echo.Context, defaultLimit int, -) (prev, next uuid.NullUUID, limit int, err *AppError) { +) (prev, next uuid.NullUUID, limit int, err error) { prevQuery := c.QueryParam("prev") nextQuery := c.QueryParam("next") sizeQuery := c.QueryParam("size") diff --git a/cmd/import_breeds/main.go b/cmd/import_breeds/main.go index 04ce15be..3d2a6e1d 100644 --- a/cmd/import_breeds/main.go +++ b/cmd/import_breeds/main.go @@ -95,7 +95,7 @@ func parseFlags() Flags { func importBreed( ctx context.Context, conn *database.DB, petType commonvo.PetType, row breedsimporterservice.Row, -) (*breed.DetailView, *pnd.AppError) { +) (*breed.DetailView, error) { log.Printf("Importing breed with pet_type: %s, name: %s to database", petType, row.Breed) existingList, err := databasegen.New(conn).FindBreeds(ctx, databasegen.FindBreedsParams{ diff --git a/cmd/import_conditions/main.go b/cmd/import_conditions/main.go index 0ef1baaf..18be41bc 100644 --- a/cmd/import_conditions/main.go +++ b/cmd/import_conditions/main.go @@ -21,9 +21,9 @@ func main() { ctx := context.Background() conditionService := service.NewSOSConditionService(db) - conditionList, err2 := conditionService.InitConditions(ctx) - if err2 != nil { - log.Fatalf("error initializing conditions: %v\n", err2) + conditionList, err := conditionService.InitConditions(ctx) + if err != nil { + log.Fatalf("error initializing conditions: %v\n", err) } log.Println("Total conditions imported: ", len(conditionList)) diff --git a/cmd/migrateuuids/main.go b/cmd/migrateuuids/main.go index 9f310169..3efcb603 100644 --- a/cmd/migrateuuids/main.go +++ b/cmd/migrateuuids/main.go @@ -46,7 +46,7 @@ func main() { pndErr := migrate(ctx, db, MigrateOptions{ReadOnly: *readOnlyPtr, Force: *forcePtr}) if pndErr != nil { - panic(pndErr.Err) + panic(pndErr) } log.Println("Completed migration") diff --git a/cmd/migrateuuids/uuidmigrator.go b/cmd/migrateuuids/uuidmigrator.go index b3cf34e2..75790b23 100644 --- a/cmd/migrateuuids/uuidmigrator.go +++ b/cmd/migrateuuids/uuidmigrator.go @@ -174,7 +174,7 @@ type MigrateOptions struct { Log bool } -func migrate(ctx context.Context, db *database.DB, options MigrateOptions) *pnd.AppError { +func migrate(ctx context.Context, db *database.DB, options MigrateOptions) error { log.Println("Migrating UUIDs for tables") tx, err := db.BeginTx(ctx) if err != nil { @@ -210,7 +210,7 @@ func migrate(ctx context.Context, db *database.DB, options MigrateOptions) *pnd. return nil } -func MigrateUUID(tx *database.Tx, options MigrateOptions) *pnd.AppError { +func MigrateUUID(tx *database.Tx, options MigrateOptions) error { type Row struct { ID int UUID *string @@ -309,7 +309,7 @@ func MigrateUUID(tx *database.Tx, options MigrateOptions) *pnd.AppError { } // FK 컬럼을 연관된 테이블의 uuid 컬럼을 조회해 업데이트 -func MigrateFK(tx *database.Tx, options MigrateOptions) *pnd.AppError { +func MigrateFK(tx *database.Tx, options MigrateOptions) error { for _, target := range Targets { log.Printf("Processing table %s\n", target.Table) diff --git a/cmd/server/handler/auth_handler.go b/cmd/server/handler/auth_handler.go index f5651ecc..417d04c8 100644 --- a/cmd/server/handler/auth_handler.go +++ b/cmd/server/handler/auth_handler.go @@ -66,12 +66,12 @@ func (h *AuthHandler) KakaoCallback(c echo.Context) error { return c.JSON(pndErr.StatusCode, pndErr) } - customToken, err2 := h.authService.CustomToken( + customToken, err := h.authService.CustomToken( c.Request().Context(), strconv.FormatInt(userProfile.ID, 10), ) - if err2 != nil { - return c.JSON(err2.StatusCode, err2) + if err != nil { + return err } return c.JSON(http.StatusOK, auth.NewKakaoCallbackView(*customToken, userProfile)) @@ -90,16 +90,15 @@ func (h *AuthHandler) KakaoCallback(c echo.Context) error { func (h *AuthHandler) GenerateFBCustomTokenFromKakao(c echo.Context) error { var tokenRequest auth.GenerateFBCustomTokenRequest if err := pnd.ParseBody(c, &tokenRequest); err != nil { - return c.JSON(err.StatusCode, err) + return err } - userProfile, err2 := h.kakaoClient.FetchUserProfile( + userProfile, err := h.kakaoClient.FetchUserProfile( c.Request().Context(), tokenRequest.OAuthToken, ) - if err2 != nil { - pndErr := pnd.ErrBadRequest(errors.New("유효하지 않은 Kakao 인증 정보입니다")) - return c.JSON(pndErr.StatusCode, pndErr) + if err != nil { + return pnd.ErrBadRequest(errors.New("유효하지 않은 Kakao 인증 정보입니다")) } customToken, err := h.authService.CustomToken( @@ -107,7 +106,7 @@ func (h *AuthHandler) GenerateFBCustomTokenFromKakao(c echo.Context) error { strconv.FormatInt(userProfile.ID, 10), ) if err != nil { - return c.JSON(err.StatusCode, err) + return err } return c.JSON( diff --git a/cmd/server/handler/breed_handler.go b/cmd/server/handler/breed_handler.go index 3d49fd91..1d196758 100644 --- a/cmd/server/handler/breed_handler.go +++ b/cmd/server/handler/breed_handler.go @@ -33,7 +33,7 @@ func (h *BreedHandler) FindBreeds(c echo.Context) error { petType := pnd.ParseOptionalStringQuery(c, "pet_type") page, size, err := pnd.ParsePaginationQueries(c, 1, 20) if err != nil { - return c.JSON(err.StatusCode, err) + return err } res, err := h.breedService.FindBreeds(c.Request().Context(), &breed.FindBreedsParams{ @@ -42,7 +42,7 @@ func (h *BreedHandler) FindBreeds(c echo.Context) error { PetType: petType, }) if err != nil { - return c.JSON(err.StatusCode, err) + return err } return c.JSON(http.StatusOK, res) diff --git a/cmd/server/handler/chat_handler.go b/cmd/server/handler/chat_handler.go index 78a21919..3a5920c1 100644 --- a/cmd/server/handler/chat_handler.go +++ b/cmd/server/handler/chat_handler.go @@ -40,12 +40,12 @@ func (h ChatHandler) FindRoomByID(c echo.Context) error { c.Request().Header.Get("Authorization"), ) if err != nil { - return c.JSON(err.StatusCode, err) + return err } roomID, err := pnd.ParseIDFromPath(c, "roomID") if err != nil { - return c.JSON(err.StatusCode, err) + return err } res, err := h.chatService.FindChatRoomByUIDAndRoomID( @@ -54,7 +54,7 @@ func (h ChatHandler) FindRoomByID(c echo.Context) error { roomID, ) if err != nil { - return c.JSON(err.StatusCode, err) + return err } return c.JSON(http.StatusOK, res) @@ -76,12 +76,12 @@ func (h ChatHandler) CreateRoom(c echo.Context) error { c.Request().Header.Get("Authorization"), ) if err != nil { - return c.JSON(err.StatusCode, err) + return err } var createRoomRequest domain.CreateRoomRequest if bodyError := pnd.ParseBody(c, &createRoomRequest); bodyError != nil { - return c.JSON(bodyError.StatusCode, err) + return err } res, err := h.chatService.CreateRoom( @@ -91,7 +91,7 @@ func (h ChatHandler) CreateRoom(c echo.Context) error { user.FirebaseUID, ) if err != nil { - return c.JSON(err.StatusCode, err) + return err } return c.JSON(http.StatusCreated, res) @@ -113,17 +113,17 @@ func (h ChatHandler) JoinChatRoom(c echo.Context) error { c.Request().Header.Get("Authorization"), ) if err != nil { - return c.JSON(err.StatusCode, err) + return err } roomID, err := pnd.ParseIDFromPath(c, "roomID") if err != nil { - return c.JSON(err.StatusCode, err) + return err } res, err := h.chatService.JoinRoom(c.Request().Context(), roomID, foundUser.FirebaseUID) if err != nil { - return c.JSON(err.StatusCode, err) + return err } return c.JSON(http.StatusOK, res) @@ -145,12 +145,12 @@ func (h ChatHandler) LeaveChatRoom(c echo.Context) error { c.Request().Header.Get("Authorization"), ) if err != nil { - return c.JSON(err.StatusCode, err) + return err } roomID, err := pnd.ParseIDFromPath(c, "roomID") if err != nil { - return c.JSON(err.StatusCode, err) + return err } res := h.chatService.LeaveRoom(c.Request().Context(), roomID, foundUser.FirebaseUID) @@ -172,12 +172,12 @@ func (h ChatHandler) FindAllRooms(c echo.Context) error { c.Request().Header.Get("Authorization"), ) if err != nil { - return c.JSON(err.StatusCode, err) + return err } rooms, err := h.chatService.FindAllByUserUID(c.Request().Context(), foundUser.FirebaseUID) if err != nil { - return c.JSON(err.StatusCode, err) + return err } return c.JSON(http.StatusOK, rooms) } @@ -198,12 +198,12 @@ func (h ChatHandler) FindAllRooms(c echo.Context) error { func (h ChatHandler) FindMessagesByRoomID(c echo.Context) error { roomID, err := pnd.ParseIDFromPath(c, "roomID") if err != nil { - return c.JSON(err.StatusCode, err) + return err } - prev, next, limit, appError := pnd.ParseCursorPaginationQueries(c, 30) - if appError != nil { - return c.JSON(appError.StatusCode, appError) + prev, next, limit, err := pnd.ParseCursorPaginationQueries(c, 30) + if err != nil { + return err } res, err := h.chatService.FindChatRoomMessagesByRoomID( @@ -214,7 +214,7 @@ func (h ChatHandler) FindMessagesByRoomID(c echo.Context) error { int64(limit), ) if err != nil { - return c.JSON(err.StatusCode, err) + return err } return c.JSON(http.StatusOK, res) diff --git a/cmd/server/handler/condition_handler.go b/cmd/server/handler/condition_handler.go index c56565b5..c37a3b7e 100644 --- a/cmd/server/handler/condition_handler.go +++ b/cmd/server/handler/condition_handler.go @@ -27,7 +27,7 @@ func NewConditionHandler(conditionService service.SOSConditionService) *Conditio func (h *ConditionHandler) FindConditions(c echo.Context) error { res, err := h.conditionService.FindConditions(c.Request().Context()) if err != nil { - return c.JSON(err.StatusCode, err) + return err } return c.JSON(http.StatusOK, res) diff --git a/cmd/server/handler/media_handler.go b/cmd/server/handler/media_handler.go index caaf6580..0e30226f 100644 --- a/cmd/server/handler/media_handler.go +++ b/cmd/server/handler/media_handler.go @@ -33,12 +33,12 @@ func NewMediaHandler(mediaService service.MediaService) *MediaHandler { func (h *MediaHandler) FindMediaByID(c echo.Context) error { id, err := pnd.ParseIDFromPath(c, "id") if err != nil { - return c.JSON(err.StatusCode, err) + return err } found, err := h.mediaService.FindMediaByID(c.Request().Context(), id) if err != nil { - return c.JSON(err.StatusCode, err) + return err } return c.JSON(http.StatusOK, found) @@ -56,39 +56,35 @@ func (h *MediaHandler) FindMediaByID(c echo.Context) error { func (h *MediaHandler) UploadImage(c echo.Context) error { fileHeader, err := c.FormFile("file") if err != nil { - pndErr := pnd.ErrMultipartFormError(errors.New("file must be provided")) - return c.JSON(pndErr.StatusCode, pndErr) + return pnd.ErrMultipartFormError(errors.New("file must be provided")) } if fileHeader.Size > 10<<20 { - pndErr := pnd.ErrMultipartFormError(errors.New("file size must be less than 10MB")) - return c.JSON(pndErr.StatusCode, pndErr) + return pnd.ErrMultipartFormError(errors.New("file size must be less than 10MB")) } file, err := fileHeader.Open() if err != nil { - pndErr := pnd.ErrMultipartFormError(errors.New("failed to open file")) - return c.JSON(pndErr.StatusCode, pndErr) + return pnd.ErrMultipartFormError(errors.New("failed to open file")) } defer file.Close() if !isValidMimeType(fileHeader.Header.Get("Content-Type")) { - pndErr := pnd.ErrMultipartFormError( + return pnd.ErrMultipartFormError( errors.New( "invalid MIME type; supported MIME types are: [" + supportedMimeTypeString() + "]", ), ) - return c.JSON(pndErr.StatusCode, pndErr) } - res, err2 := h.mediaService.UploadMedia( + res, err := h.mediaService.UploadMedia( c.Request().Context(), file, media.TypeImage, fileHeader.Filename, ) - if err2 != nil { - return c.JSON(err2.StatusCode, err2) + if err != nil { + return err } return c.JSON(http.StatusCreated, res) diff --git a/cmd/server/handler/sos_post_handler.go b/cmd/server/handler/sos_post_handler.go index 6515385f..d8039042 100644 --- a/cmd/server/handler/sos_post_handler.go +++ b/cmd/server/handler/sos_post_handler.go @@ -41,12 +41,12 @@ func (h *SOSPostHandler) WriteSOSPost(c echo.Context) error { c.Request().Header.Get("Authorization"), ) if err != nil { - return c.JSON(err.StatusCode, err) + return err } var writeSOSPostRequest sospost.WriteSOSPostRequest if err = pnd.ParseBody(c, &writeSOSPostRequest); err != nil { - return c.JSON(err.StatusCode, err) + return err } res, err := h.sosPostService.WriteSOSPost( @@ -55,7 +55,7 @@ func (h *SOSPostHandler) WriteSOSPost(c echo.Context) error { &writeSOSPostRequest, ) if err != nil { - return c.JSON(err.StatusCode, err) + return err } return c.JSON(http.StatusCreated, res) @@ -77,7 +77,7 @@ func (h *SOSPostHandler) WriteSOSPost(c echo.Context) error { func (h *SOSPostHandler) FindSOSPosts(c echo.Context) error { authorID, err := pnd.ParseOptionalUUIDQuery(c, "author_id") if err != nil { - return c.JSON(err.StatusCode, err) + return err } sortBy := "newest" @@ -91,7 +91,7 @@ func (h *SOSPostHandler) FindSOSPosts(c echo.Context) error { page, size, err := pnd.ParsePaginationQueries(c, 1, 20) if err != nil { - return c.JSON(err.StatusCode, err) + return err } var res *sospost.FindSOSPostListView @@ -99,12 +99,12 @@ func (h *SOSPostHandler) FindSOSPosts(c echo.Context) error { res, err = h.sosPostService.FindSOSPostsByAuthorID( c.Request().Context(), authorID.UUID, page, size, sortBy, filterType) if err != nil { - return c.JSON(err.StatusCode, err) + return err } } else { res, err = h.sosPostService.FindSOSPosts(c.Request().Context(), page, size, sortBy, filterType) if err != nil { - return c.JSON(err.StatusCode, err) + return err } } @@ -122,11 +122,11 @@ func (h *SOSPostHandler) FindSOSPosts(c echo.Context) error { func (h *SOSPostHandler) FindSOSPostByID(c echo.Context) error { id, err := pnd.ParseIDFromPath(c, "id") if err != nil { - return c.JSON(err.StatusCode, err) + return err } res, err := h.sosPostService.FindSOSPostByID(c.Request().Context(), id) if err != nil { - return c.JSON(err.StatusCode, err) + return err } return c.JSON(http.StatusOK, res) @@ -148,12 +148,12 @@ func (h *SOSPostHandler) UpdateSOSPost(c echo.Context) error { c.Request().Header.Get("Authorization"), ) if err != nil { - return c.JSON(err.StatusCode, err) + return err } var updateSOSPostRequest sospost.UpdateSOSPostRequest if err = pnd.ParseBody(c, &updateSOSPostRequest); err != nil { - return c.JSON(err.StatusCode, err) + return err } permission, err := h.sosPostService.CheckUpdatePermission( @@ -162,16 +162,15 @@ func (h *SOSPostHandler) UpdateSOSPost(c echo.Context) error { updateSOSPostRequest.ID, ) if err != nil { - return c.JSON(err.StatusCode, err) + return err } if !permission { - pndErr := pnd.ErrForbidden(errors.New("해당 게시글에 대한 수정 권한이 없습니다")) - return c.JSON(pndErr.StatusCode, pndErr) + return pnd.ErrForbidden(errors.New("해당 게시글에 대한 수정 권한이 없습니다")) } res, err := h.sosPostService.UpdateSOSPost(c.Request().Context(), &updateSOSPostRequest) if err != nil { - return c.JSON(err.StatusCode, err) + return err } return c.JSON(http.StatusOK, res) diff --git a/cmd/server/handler/user_handler.go b/cmd/server/handler/user_handler.go index 4d436b53..7d0fd63a 100644 --- a/cmd/server/handler/user_handler.go +++ b/cmd/server/handler/user_handler.go @@ -37,12 +37,12 @@ func NewUserHandler(userService service.UserService, authService service.AuthSer func (h *UserHandler) RegisterUser(c echo.Context) error { var registerUserRequest user.RegisterUserRequest if err := pnd.ParseBody(c, ®isterUserRequest); err != nil { - return c.JSON(err.StatusCode, err) + return err } res, err := h.userService.RegisterUser(c.Request().Context(), ®isterUserRequest) if err != nil { - return c.JSON(err.StatusCode, err) + return err } return c.JSON(http.StatusCreated, res) @@ -60,7 +60,7 @@ func (h *UserHandler) RegisterUser(c echo.Context) error { func (h *UserHandler) CheckUserNickname(c echo.Context) error { var checkUserNicknameRequest user.CheckNicknameRequest if err := pnd.ParseBody(c, &checkUserNicknameRequest); err != nil { - return c.JSON(err.StatusCode, err) + return err } exists, err := h.userService.ExistsByNickname( @@ -68,7 +68,7 @@ func (h *UserHandler) CheckUserNickname(c echo.Context) error { checkUserNicknameRequest.Nickname, ) if err != nil { - return c.JSON(err.StatusCode, err) + return err } return c.JSON(http.StatusOK, user.CheckNicknameView{IsAvailable: !exists}) @@ -86,7 +86,7 @@ func (h *UserHandler) CheckUserNickname(c echo.Context) error { func (h *UserHandler) FindUserStatusByEmail(c echo.Context) error { var providerRequest user.UserStatusRequest if err := pnd.ParseBody(c, &providerRequest); err != nil { - return c.JSON(err.StatusCode, err) + return err } userData, err := h.userService.FindUser( @@ -119,13 +119,13 @@ func (h *UserHandler) FindUsers(c echo.Context) error { c.Request().Header.Get("Authorization"), ) if err != nil { - return c.JSON(err.StatusCode, err) + return err } nickname := pnd.ParseOptionalStringQuery(c, "nickname") page, size, err := pnd.ParsePaginationQueries(c, 1, 10) if err != nil { - return c.JSON(err.StatusCode, err) + return err } var res *user.ListWithoutPrivateInfo @@ -133,7 +133,7 @@ func (h *UserHandler) FindUsers(c echo.Context) error { res, err = h.userService.FindUsers(c.Request().Context(), user.FindUsersParams{Page: page, Size: size, Nickname: nickname}) if err != nil { - return c.JSON(err.StatusCode, err) + return err } return c.JSON(http.StatusOK, res) @@ -154,12 +154,12 @@ func (h *UserHandler) FindUserByID(c echo.Context) error { c.Request().Header.Get("Authorization"), ) if err != nil { - return c.JSON(err.StatusCode, err) + return err } userID, err := pnd.ParseIDFromPath(c, "userID") if err != nil { - return c.JSON(err.StatusCode, err) + return err } res, err := h.userService.FindUserProfile( @@ -167,7 +167,7 @@ func (h *UserHandler) FindUserByID(c echo.Context) error { user.FindUserParams{ID: uuid.NullUUID{UUID: userID, Valid: true}}, ) if err != nil { - return c.JSON(err.StatusCode, err) + return err } return c.JSON(http.StatusOK, res) @@ -187,7 +187,7 @@ func (h *UserHandler) FindMyProfile(c echo.Context) error { c.Request().Header.Get("Authorization"), ) if err != nil { - return c.JSON(err.StatusCode, err) + return err } return c.JSON(http.StatusOK, res.ToMyProfileView()) @@ -209,14 +209,14 @@ func (h *UserHandler) UpdateMyProfile(c echo.Context) error { c.Request().Header.Get("Authorization"), ) if err != nil { - return c.JSON(err.StatusCode, err) + return err } uid := foundUser.FirebaseUID var updateUserRequest user.UpdateUserRequest if err = pnd.ParseBody(c, &updateUserRequest); err != nil { - return c.JSON(err.StatusCode, err) + return err } view, err := h.userService.UpdateUserByUID( @@ -226,7 +226,7 @@ func (h *UserHandler) UpdateMyProfile(c echo.Context) error { updateUserRequest.ProfileImageID, ) if err != nil { - return c.JSON(err.StatusCode, err) + return err } return c.JSON(http.StatusOK, view) @@ -245,11 +245,11 @@ func (h *UserHandler) DeleteMyAccount(c echo.Context) error { c.Request().Header.Get("Authorization"), ) if err != nil { - return c.JSON(err.StatusCode, err) + return err } if err := h.userService.DeleteUserByUID(c.Request().Context(), loggedInUser.FirebaseUID); err != nil { - return c.JSON(err.StatusCode, err) + return err } return c.NoContent(http.StatusNoContent) @@ -271,18 +271,18 @@ func (h *UserHandler) AddMyPets(c echo.Context) error { c.Request().Header.Get("Authorization"), ) if err != nil { - return c.JSON(err.StatusCode, err) + return err } uid := foundUser.FirebaseUID var addPetsToOwnerRequest pet.AddPetsToOwnerRequest if err := pnd.ParseBody(c, &addPetsToOwnerRequest); err != nil { - return c.JSON(err.StatusCode, err) + return err } if _, err := h.userService.AddPetsToOwner(c.Request().Context(), uid, addPetsToOwnerRequest); err != nil { - return c.JSON(err.StatusCode, err) + return err } return c.NoContent(http.StatusOK) @@ -302,7 +302,7 @@ func (h *UserHandler) FindMyPets(c echo.Context) error { c.Request().Header.Get("Authorization"), ) if err != nil { - return c.JSON(err.StatusCode, err) + return err } res, err := h.userService.FindPets(c.Request().Context(), pet.FindPetsParams{ @@ -312,7 +312,7 @@ func (h *UserHandler) FindMyPets(c echo.Context) error { }, ) if err != nil { - return c.JSON(err.StatusCode, err) + return err } return c.JSON(http.StatusOK, res) @@ -335,23 +335,23 @@ func (h *UserHandler) UpdateMyPet(c echo.Context) error { c.Request().Header.Get("Authorization"), ) if err != nil { - return c.JSON(err.StatusCode, err) + return err } uid := foundUser.FirebaseUID petID, err := pnd.ParseIDFromPath(c, "petID") if err != nil { - return c.JSON(err.StatusCode, err) + return err } var updatePetRequest pet.UpdatePetRequest if err = pnd.ParseBody(c, &updatePetRequest); err != nil { - return c.JSON(err.StatusCode, err) + return err } res, err := h.userService.UpdatePet(c.Request().Context(), uid, petID, updatePetRequest) if err != nil { - return c.JSON(err.StatusCode, err) + return err } return c.JSON(http.StatusOK, res) @@ -371,17 +371,17 @@ func (h *UserHandler) DeleteMyPet(c echo.Context) error { c.Request().Header.Get("Authorization"), ) if err != nil { - return c.JSON(err.StatusCode, err) + return err } uid := foundUser.FirebaseUID petID, err := pnd.ParseIDFromPath(c, "petID") if err != nil { - return c.JSON(err.StatusCode, err) + return err } if err := h.userService.DeletePet(c.Request().Context(), uid, petID); err != nil { - return c.JSON(err.StatusCode, err) + return err } return c.NoContent(http.StatusNoContent) diff --git a/cmd/server/router.go b/cmd/server/router.go index 6476801e..383bec98 100644 --- a/cmd/server/router.go +++ b/cmd/server/router.go @@ -2,10 +2,13 @@ package main import ( "context" + "errors" "fmt" "net/http" "os" + pnd "github.com/pet-sitter/pets-next-door-api/api" + "github.com/labstack/echo/v4" "github.com/labstack/echo/v4/middleware" "github.com/pet-sitter/pets-next-door-api/cmd/server/handler" @@ -89,6 +92,24 @@ func NewRouter(app *firebaseinfra.FirebaseApp) (*echo.Echo, error) { return nil }, })) + + // Error handler + e.Use(func(next echo.HandlerFunc) echo.HandlerFunc { + return func(c echo.Context) error { + err := next(c) + if err != nil { + var appErr *pnd.AppError + if errors.As(err, &appErr) { + return c.JSON(appErr.StatusCode, appErr) + } + + return c.JSON(http.StatusInternalServerError, pnd.ErrUnknown(err)) + } + + return err + } + }) + e.Use(pndmiddleware.BuildAuthMiddleware(authService, auth.FirebaseAuthClientKey)) // Register routes diff --git a/internal/common/null.go b/internal/common/null.go index 977d4af0..4c597d12 100644 --- a/internal/common/null.go +++ b/internal/common/null.go @@ -100,7 +100,7 @@ func Int64PtrToNullInt32(val *int64) sql.NullInt32 { } } -func StrToNullTime(val string) (sql.NullTime, *pnd.AppError) { +func StrToNullTime(val string) (sql.NullTime, error) { const timeLayout = "2006-01-02" parsedTime, err := time.Parse(timeLayout, val) if err != nil { diff --git a/internal/datatype/uuid.go b/internal/datatype/uuid.go index d17251b1..c3e61ca7 100644 --- a/internal/datatype/uuid.go +++ b/internal/datatype/uuid.go @@ -5,7 +5,7 @@ import ( pnd "github.com/pet-sitter/pets-next-door-api/api" ) -func NewV7() (uuid.UUID, *pnd.AppError) { +func NewV7() (uuid.UUID, error) { id, err := uuid.NewV7() if err != nil { return uuid.Nil, pnd.ErrUnknown(err) diff --git a/internal/infra/bucket/client.go b/internal/infra/bucket/client.go index 73d1af40..da78ef7c 100644 --- a/internal/infra/bucket/client.go +++ b/internal/infra/bucket/client.go @@ -17,7 +17,7 @@ import ( ) type FileUploader interface { - UploadFile(file io.ReadSeeker, fileName string) (url string, appError *pnd.AppError) + UploadFile(file io.ReadSeeker, fileName string) (string, error) } type S3Client struct { @@ -45,7 +45,7 @@ func NewS3Client(keyID, key, endpoint, region, bucketName string) (*S3Client, er }, nil } -func (c *S3Client) UploadFile(file io.ReadSeeker, fileName string) (string, *pnd.AppError) { +func (c *S3Client) UploadFile(file io.ReadSeeker, fileName string) (string, error) { randomFileName := generateRandomFileName(fileName) fullPath := "media/" + randomFileName diff --git a/internal/infra/database/transaction.go b/internal/infra/database/transaction.go index 137d1d68..4ad299c0 100644 --- a/internal/infra/database/transaction.go +++ b/internal/infra/database/transaction.go @@ -11,13 +11,13 @@ import ( ) type Transactioner interface { - Rollback() *pnd.AppError - Commit() *pnd.AppError - EndTx(f func() *pnd.AppError) *pnd.AppError - BeginTx() (*DB, *pnd.AppError) + Rollback() error + Commit() error + EndTx(f func() error) error + BeginTx() (*DB, error) } -func (db *DB) BeginTx(ctx context.Context) (*Tx, *pnd.AppError) { +func (db *DB) BeginTx(ctx context.Context) (*Tx, error) { tx, err := db.DB.BeginTx(ctx, nil) if err != nil { return nil, pnd.FromPostgresError(err) @@ -26,8 +26,8 @@ func (db *DB) BeginTx(ctx context.Context) (*Tx, *pnd.AppError) { return &Tx{tx}, nil } -func (tx *Tx) EndTx(f func() *pnd.AppError) *pnd.AppError { - var err *pnd.AppError +func (tx *Tx) EndTx(f func() error) error { + var err error defer func() { if p := recover(); p != nil { if err2 := tx.Tx.Rollback(); err2 != nil { @@ -49,7 +49,7 @@ func (tx *Tx) EndTx(f func() *pnd.AppError) *pnd.AppError { return err } -func (tx *Tx) Rollback() *pnd.AppError { +func (tx *Tx) Rollback() error { if err := tx.Tx.Rollback(); err != nil { if errors.Is(err, sql.ErrTxDone) { return nil @@ -60,7 +60,7 @@ func (tx *Tx) Rollback() *pnd.AppError { return nil } -func (tx *Tx) Commit() *pnd.AppError { +func (tx *Tx) Commit() error { if err := tx.Tx.Commit(); err != nil { return pnd.FromPostgresError(err) } @@ -68,7 +68,7 @@ func (tx *Tx) Commit() *pnd.AppError { return nil } -func WithTransaction(ctx context.Context, conn *DB, f func(tx *Tx) *pnd.AppError) *pnd.AppError { +func WithTransaction(ctx context.Context, conn *DB, f func(tx *Tx) error) error { tx, err := conn.BeginTx(ctx) if err != nil { return err diff --git a/internal/service/auth_service.go b/internal/service/auth_service.go index 5269fdf9..d6f24520 100644 --- a/internal/service/auth_service.go +++ b/internal/service/auth_service.go @@ -11,8 +11,8 @@ import ( ) type AuthService interface { - VerifyAuthAndGetUser(ctx context.Context, authHeader string) (*user.InternalView, *pnd.AppError) - CustomToken(ctx context.Context, uid string) (*string, *pnd.AppError) + VerifyAuthAndGetUser(ctx context.Context, authHeader string) (*user.InternalView, error) + CustomToken(ctx context.Context, uid string) (*string, error) } type FirebaseBearerAuthService struct { @@ -32,15 +32,15 @@ func NewFirebaseBearerAuthService( func (service *FirebaseBearerAuthService) verifyAuth( ctx context.Context, authHeader string, -) (*auth.Token, *pnd.AppError) { +) (*auth.Token, error) { idToken, err := service.stripBearerToken(authHeader) if err != nil { return nil, err } - authToken, err2 := service.authClient.VerifyIDToken(ctx, idToken) - if err2 != nil { - return nil, pnd.ErrInvalidFBToken(err2) + authToken, err := service.authClient.VerifyIDToken(ctx, idToken) + if err != nil { + return nil, pnd.ErrInvalidFBToken(err) } return authToken, nil @@ -48,7 +48,7 @@ func (service *FirebaseBearerAuthService) verifyAuth( func (service *FirebaseBearerAuthService) VerifyAuthAndGetUser( ctx context.Context, authHeader string, -) (*user.InternalView, *pnd.AppError) { +) (*user.InternalView, error) { authToken, err := service.verifyAuth(ctx, authHeader) if err != nil { return nil, err @@ -65,7 +65,7 @@ func (service *FirebaseBearerAuthService) VerifyAuthAndGetUser( func (service *FirebaseBearerAuthService) CustomToken( ctx context.Context, uid string, -) (*string, *pnd.AppError) { +) (*string, error) { customToken, err := service.authClient.CustomToken(ctx, uid) if err != nil { return nil, pnd.ErrUnknown(err) @@ -76,7 +76,7 @@ func (service *FirebaseBearerAuthService) CustomToken( func (service *FirebaseBearerAuthService) stripBearerToken( authHeader string, -) (string, *pnd.AppError) { +) (string, error) { if len(authHeader) > 6 && strings.ToUpper(authHeader[0:7]) == "BEARER " { return authHeader[7:], nil } diff --git a/internal/service/breed_service.go b/internal/service/breed_service.go index 33ff663c..918920d4 100644 --- a/internal/service/breed_service.go +++ b/internal/service/breed_service.go @@ -22,7 +22,7 @@ func NewBreedService(conn *database.DB) *BreedService { func (s *BreedService) FindBreeds( ctx context.Context, params *breed.FindBreedsParams, -) (*breed.ListView, *pnd.AppError) { +) (*breed.ListView, error) { rows, err := databasegen.New(s.conn).FindBreeds(ctx, params.ToDBParams()) if err != nil { return nil, pnd.FromPostgresError(err) diff --git a/internal/service/chat_service.go b/internal/service/chat_service.go index 11fb28b9..f28e0b7c 100644 --- a/internal/service/chat_service.go +++ b/internal/service/chat_service.go @@ -27,7 +27,7 @@ func NewChatService(conn *database.DB) *ChatService { func (s *ChatService) CreateRoom( ctx context.Context, name, roomType, userFirebaseUID string, ) ( - *chat.RoomSimpleInfo, *pnd.AppError, + *chat.RoomSimpleInfo, error, ) { userData, err := databasegen.New(s.conn).FindUser(ctx, databasegen.FindUserParams{ FbUid: utils.StrToNullStr(userFirebaseUID), @@ -65,17 +65,18 @@ func (s *ChatService) CreateRoom( return nil, pnd.ErrUnknown(fmt.Errorf("failed to generate UUID: %w", joinRoomUUIDError)) } - _, err3 := q.JoinRoom(ctx, databasegen.JoinRoomParams{ + _, err = q.JoinRoom(ctx, databasegen.JoinRoomParams{ ID: joinRoomUUID, UserID: userData.ID, RoomID: row.ID, }) - - if err3 != nil { - return nil, pnd.FromPostgresError(err3) + if err != nil { + return nil, pnd.FromPostgresError(err) } - tx.Commit() + if err := tx.Commit(); err != nil { + return nil, err + } return chat.ToCreateRoom(row, chat.ToJoinUsers(userData)), nil } @@ -84,7 +85,7 @@ func (s *ChatService) JoinRoom( ctx context.Context, roomID uuid.UUID, fbUID string, -) (*chat.JoinRoom, *pnd.AppError) { +) (*chat.JoinRoom, error) { userData, err := databasegen.New(s.conn).FindUser(ctx, databasegen.FindUserParams{ FbUid: utils.StrToNullStr(fbUID), }) @@ -131,7 +132,7 @@ func (s *ChatService) JoinRoom( return nil, pnd.ErrBadRequest(errors.New("user already joined in the room")) } -func (s *ChatService) LeaveRoom(ctx context.Context, roomID uuid.UUID, fbUID string) *pnd.AppError { +func (s *ChatService) LeaveRoom(ctx context.Context, roomID uuid.UUID, fbUID string) error { userData, err := databasegen.New(s.conn).FindUser(ctx, databasegen.FindUserParams{ FbUid: utils.StrToNullStr(fbUID), }) @@ -163,7 +164,7 @@ func (s *ChatService) LeaveRoom(ctx context.Context, roomID uuid.UUID, fbUID str func (s *ChatService) FindAllByUserUID( ctx context.Context, fbUID string, -) (*chat.JoinRoomsView, *pnd.AppError) { +) (*chat.JoinRoomsView, error) { userData, err := databasegen.New(s.conn).FindUser(ctx, databasegen.FindUserParams{ FbUid: utils.StrToNullStr(fbUID), }) @@ -184,7 +185,7 @@ func (s *ChatService) FindChatRoomByUIDAndRoomID( fbUID string, roomID uuid.UUID, ) ( - *chat.RoomSimpleInfo, *pnd.AppError, + *chat.RoomSimpleInfo, error, ) { userData, err := databasegen.New(s.conn).FindUser(ctx, databasegen.FindUserParams{ FbUid: utils.StrToNullStr(fbUID), @@ -211,7 +212,7 @@ func (s *ChatService) FindChatRoomByUIDAndRoomID( */ func (s *ChatService) FindChatRoomMessagesByRoomID( ctx context.Context, roomID uuid.UUID, prev, next uuid.NullUUID, limit int64, -) (*chat.MessageCursorView, *pnd.AppError) { +) (*chat.MessageCursorView, error) { // prev와 next에 따라 다른 쿼리를 실행 if prev.Valid && next.Valid { // prev와 next 모두 존재하는 경우 @@ -361,7 +362,7 @@ func (s *ChatService) FindChatRoomMessagesByRoomID( // hasPrev 메시지가 있는지 확인 func (s *ChatService) HasPrevMessages( ctx context.Context, roomID, messageID uuid.UUID, -) (bool, *pnd.AppError) { +) (bool, error) { hasPrev, err := databasegen.New(s.conn).HasPrevMessages(ctx, databasegen.HasPrevMessagesParams{ ID: messageID, RoomID: roomID, @@ -376,7 +377,7 @@ func (s *ChatService) HasPrevMessages( // hasNext 메시지가 있는지 확인 func (s *ChatService) HasNextMessages( ctx context.Context, roomID, messageID uuid.UUID, -) (bool, *pnd.AppError) { +) (bool, error) { hasNext, err := databasegen.New(s.conn).HasNextMessages(ctx, databasegen.HasNextMessagesParams{ ID: messageID, RoomID: roomID, diff --git a/internal/service/media_service.go b/internal/service/media_service.go index 6b879126..b5082098 100644 --- a/internal/service/media_service.go +++ b/internal/service/media_service.go @@ -36,7 +36,7 @@ type UploadFileView struct { func (s *MediaService) UploadMedia( ctx context.Context, file io.ReadSeeker, mediaType media.Type, fileName string, -) (*media.DetailView, *pnd.AppError) { +) (*media.DetailView, error) { url, err := s.uploader.UploadFile(file, fileName) if err != nil { return nil, err @@ -52,20 +52,20 @@ func (s *MediaService) UploadMedia( func (s *MediaService) CreateMedia( ctx context.Context, mediaType media.Type, url string, -) (*media.DetailView, *pnd.AppError) { +) (*media.DetailView, error) { tx, err := s.conn.BeginTx(ctx) defer tx.Rollback() if err != nil { return nil, err } - created, err2 := databasegen.New(s.conn).CreateMedia(ctx, databasegen.CreateMediaParams{ + created, err := databasegen.New(s.conn).CreateMedia(ctx, databasegen.CreateMediaParams{ ID: datatype.NewUUIDV7(), MediaType: mediaType.String(), Url: url, }) - if err2 != nil { - return nil, pnd.FromPostgresError(err2) + if err != nil { + return nil, pnd.FromPostgresError(err) } if err := tx.Commit(); err != nil { @@ -77,7 +77,7 @@ func (s *MediaService) CreateMedia( func (s *MediaService) FindMediaByID( ctx context.Context, id uuid.UUID, -) (*media.DetailView, *pnd.AppError) { +) (*media.DetailView, error) { mediaData, err := databasegen.New(s.conn). FindSingleMedia(ctx, databasegen.FindSingleMediaParams{ ID: uuid.NullUUID{UUID: id, Valid: true}, @@ -92,7 +92,7 @@ func (s *MediaService) FindMediaByID( func (s *MediaService) FindMediasByIDs( ctx context.Context, ids []uuid.UUID, -) ([]media.DetailView, *pnd.AppError) { +) ([]media.DetailView, error) { if len(ids) == 0 { return make([]media.DetailView, 0), nil } diff --git a/internal/service/sos_condition_service.go b/internal/service/sos_condition_service.go index de3e9807..57a0f254 100644 --- a/internal/service/sos_condition_service.go +++ b/internal/service/sos_condition_service.go @@ -26,7 +26,7 @@ func NewSOSConditionService(conn *database.DB) *SOSConditionService { func (service *SOSConditionService) InitConditions( ctx context.Context, -) (soscondition.ListView, *pnd.AppError) { +) (soscondition.ListView, error) { tx, err := service.conn.BeginTx(ctx) if err != nil { return nil, err @@ -56,7 +56,7 @@ func (service *SOSConditionService) InitConditions( func (service *SOSConditionService) FindConditions( ctx context.Context, -) (soscondition.ListView, *pnd.AppError) { +) (soscondition.ListView, error) { conditionList, err := databasegen.New(service.conn).FindConditions(ctx, false) if err != nil { return nil, pnd.FromPostgresError(err) diff --git a/internal/service/sos_post_service.go b/internal/service/sos_post_service.go index 6b8f97d4..a32fc3c6 100644 --- a/internal/service/sos_post_service.go +++ b/internal/service/sos_post_service.go @@ -31,7 +31,7 @@ func NewSOSPostService(conn *database.DB) *SOSPostService { func (service *SOSPostService) WriteSOSPost( ctx context.Context, fbUID string, request *sospost.WriteSOSPostRequest, -) (*sospost.DetailView, *pnd.AppError) { +) (*sospost.DetailView, error) { tx, err := service.conn.BeginTx(ctx) defer tx.Rollback() if err != nil { @@ -39,11 +39,11 @@ func (service *SOSPostService) WriteSOSPost( } q := databasegen.New(tx) - userData, err2 := q.FindUser(ctx, databasegen.FindUserParams{ + userData, err := q.FindUser(ctx, databasegen.FindUserParams{ FbUid: utils.StrToNullStr(fbUID), }) - if err2 != nil { - return nil, pnd.FromPostgresError(err2) + if err != nil { + return nil, pnd.FromPostgresError(err) } thumbnailID := setThumbnailID(request.ImageIDs) @@ -56,29 +56,29 @@ func (service *SOSPostService) WriteSOSPost( return nil, err } - mediaData, err2 := q.FindResourceMedia(ctx, databasegen.FindResourceMediaParams{ + mediaData, err := q.FindResourceMedia(ctx, databasegen.FindResourceMediaParams{ ResourceID: uuid.NullUUID{UUID: sosPost.ID, Valid: true}, ResourceType: utils.StrToNullStr(resourcemedia.SOSResourceType.String()), }) - if err2 != nil { - return nil, pnd.FromPostgresError(err2) + if err != nil { + return nil, pnd.FromPostgresError(err) } - conditionList, err2 := q.FindSOSPostConditions(ctx, databasegen.FindSOSPostConditionsParams{ + conditionList, err := q.FindSOSPostConditions(ctx, databasegen.FindSOSPostConditionsParams{ SosPostID: sosPost.ID, }) - if err2 != nil { - return nil, pnd.FromPostgresError(err2) + if err != nil { + return nil, pnd.FromPostgresError(err) } - petRows, err2 := q.FindPetsBySOSPostID(ctx, sosPost.ID) - if err2 != nil { - return nil, pnd.FromPostgresError(err2) + petRows, err := q.FindPetsBySOSPostID(ctx, sosPost.ID) + if err != nil { + return nil, pnd.FromPostgresError(err) } - dates, err2 := q.FindDatesBySOSPostID(ctx, uuid.NullUUID{UUID: sosPost.ID, Valid: true}) - if err2 != nil { - return nil, pnd.FromPostgresError(err2) + dates, err := q.FindDatesBySOSPostID(ctx, uuid.NullUUID{UUID: sosPost.ID, Valid: true}) + if err != nil { + return nil, pnd.FromPostgresError(err) } if err := tx.Commit(); err != nil { @@ -97,7 +97,7 @@ func (service *SOSPostService) WriteSOSPost( func (service *SOSPostService) createSOSPost( ctx context.Context, q *databasegen.Queries, authorID uuid.UUID, request *sospost.WriteSOSPostRequest, thumbnailID uuid.NullUUID, -) (databasegen.WriteSOSPostRow, *pnd.AppError) { +) (databasegen.WriteSOSPostRow, error) { params := databasegen.WriteSOSPostParams{ ID: datatype.NewUUIDV7(), AuthorID: authorID, @@ -126,7 +126,7 @@ func (service *SOSPostService) saveAllLinks( q *databasegen.Queries, request *sospost.WriteSOSPostRequest, sosPostID uuid.UUID, -) *pnd.AppError { +) error { if err := service.SaveSOSDates(ctx, q, request.Dates, sosPostID); err != nil { return err } @@ -141,22 +141,22 @@ func (service *SOSPostService) saveAllLinks( func (service *SOSPostService) FindSOSPosts( ctx context.Context, page, size int, sortBy, filterType string, -) (*sospost.FindSOSPostListView, *pnd.AppError) { +) (*sospost.FindSOSPostListView, error) { tx, err := service.conn.BeginTx(ctx) defer tx.Rollback() if err != nil { return nil, err } - sosPosts, err2 := databasegen.New(tx).FindSOSPosts(ctx, databasegen.FindSOSPostsParams{ + sosPosts, err := databasegen.New(tx).FindSOSPosts(ctx, databasegen.FindSOSPostsParams{ EarliestDateStartAt: utils.FormatDateString(time.Now().String()), PetType: utils.StrToNullStr(filterType), SortBy: utils.StrToNullStr(sortBy), Limit: utils.IntToNullInt32(size + 1), Offset: utils.IntToNullInt32((page - 1) * size), }) - if err2 != nil { - return nil, pnd.FromPostgresError(err2) + if err != nil { + return nil, pnd.FromPostgresError(err) } sosPostInfoList := sospost.ToInfoListFromFindRow(sosPosts, page, size) @@ -189,14 +189,14 @@ func (service *SOSPostService) FindSOSPosts( func (service *SOSPostService) FindSOSPostsByAuthorID( ctx context.Context, authorID uuid.UUID, page, size int, sortBy, filterType string, -) (*sospost.FindSOSPostListView, *pnd.AppError) { +) (*sospost.FindSOSPostListView, error) { tx, err := service.conn.BeginTx(ctx) defer tx.Rollback() if err != nil { return nil, err } - sosPosts, err2 := databasegen.New(tx). + sosPosts, err := databasegen.New(tx). FindSOSPostsByAuthorID(ctx, databasegen.FindSOSPostsByAuthorIDParams{ EarliestDateStartAt: utils.FormatDateString(time.Now().String()), PetType: utils.StrToNullStr(filterType), @@ -205,8 +205,8 @@ func (service *SOSPostService) FindSOSPostsByAuthorID( Limit: utils.IntToNullInt32(size + 1), Offset: utils.IntToNullInt32((page - 1) * size), }) - if err2 != nil { - return nil, pnd.FromPostgresError(err2) + if err != nil { + return nil, pnd.FromPostgresError(err) } sosPostInfoList := sospost.ToInfoListFromFindAuthorIDRow(sosPosts, page, size) @@ -240,25 +240,25 @@ func (service *SOSPostService) FindSOSPostsByAuthorID( func (service *SOSPostService) FindSOSPostByID( ctx context.Context, id uuid.UUID, -) (*sospost.FindSOSPostView, *pnd.AppError) { +) (*sospost.FindSOSPostView, error) { tx, err := service.conn.BeginTx(ctx) defer tx.Rollback() if err != nil { return nil, err } - sosPost, err2 := databasegen.New(tx).FindSOSPostByID(ctx, uuid.NullUUID{UUID: id, Valid: true}) - if err2 != nil { - return nil, pnd.FromPostgresError(err2) + sosPost, err := databasegen.New(tx).FindSOSPostByID(ctx, uuid.NullUUID{UUID: id, Valid: true}) + if err != nil { + return nil, pnd.FromPostgresError(err) } sosPostInfo := sospost.ToInfoFromFindByIDRow(sosPost) - author, err2 := databasegen.New(tx).FindUser(ctx, databasegen.FindUserParams{ + author, err := databasegen.New(tx).FindUser(ctx, databasegen.FindUserParams{ ID: uuid.NullUUID{UUID: sosPostInfo.AuthorID, Valid: true}, IncludeDeleted: true, }) - if err2 != nil { - return nil, pnd.FromPostgresError(err2) + if err != nil { + return nil, pnd.FromPostgresError(err) } if err := tx.Commit(); err != nil { @@ -280,7 +280,7 @@ func (service *SOSPostService) FindSOSPostByID( func (service *SOSPostService) UpdateSOSPost( ctx context.Context, request *sospost.UpdateSOSPostRequest, -) (*sospost.DetailView, *pnd.AppError) { +) (*sospost.DetailView, error) { tx, err := service.conn.BeginTx(ctx) defer tx.Rollback() if err != nil { @@ -288,8 +288,8 @@ func (service *SOSPostService) UpdateSOSPost( } q := databasegen.New(tx) - if err2 := service.updateAllLinks(ctx, q, request); err2 != nil { - return nil, err2 + if err = service.updateAllLinks(ctx, q, request); err != nil { + return nil, err } thumbnailID := setThumbnailID(request.ImageIDs) @@ -298,31 +298,31 @@ func (service *SOSPostService) UpdateSOSPost( return nil, err } - mediaData, err2 := databasegen.New(tx). + mediaData, err := databasegen.New(tx). FindResourceMedia(ctx, databasegen.FindResourceMediaParams{ ResourceID: uuid.NullUUID{UUID: updateSOSPost.ID, Valid: true}, ResourceType: utils.StrToNullStr(resourcemedia.SOSResourceType.String()), }) - if err2 != nil { - return nil, pnd.FromPostgresError(err2) + if err != nil { + return nil, pnd.FromPostgresError(err) } - conditionList, err2 := databasegen.New(tx). + conditionList, err := databasegen.New(tx). FindSOSPostConditions(ctx, databasegen.FindSOSPostConditionsParams{ SosPostID: updateSOSPost.ID, }) - if err2 != nil { - return nil, pnd.FromPostgresError(err2) + if err != nil { + return nil, pnd.FromPostgresError(err) } - petRows, err2 := databasegen.New(tx).FindPetsBySOSPostID(ctx, updateSOSPost.ID) - if err2 != nil { - return nil, pnd.FromPostgresError(err2) + petRows, err := databasegen.New(tx).FindPetsBySOSPostID(ctx, updateSOSPost.ID) + if err != nil { + return nil, pnd.FromPostgresError(err) } - dates, err2 := q.FindDatesBySOSPostID(ctx, uuid.NullUUID{UUID: request.ID, Valid: true}) - if err2 != nil { - return nil, pnd.FromPostgresError(err2) + dates, err := q.FindDatesBySOSPostID(ctx, uuid.NullUUID{UUID: request.ID, Valid: true}) + if err != nil { + return nil, pnd.FromPostgresError(err) } if err := tx.Commit(); err != nil { @@ -343,7 +343,7 @@ func (service *SOSPostService) updateSOSPost( q *databasegen.Queries, request *sospost.UpdateSOSPostRequest, thumbnailID uuid.NullUUID, -) (databasegen.UpdateSOSPostRow, *pnd.AppError) { +) (databasegen.UpdateSOSPostRow, error) { params := databasegen.UpdateSOSPostParams{ ID: request.ID, Title: utils.StrToNullStr(request.Title), @@ -368,7 +368,7 @@ func (service *SOSPostService) updateSOSPost( func (service *SOSPostService) updateAllLinks( ctx context.Context, q *databasegen.Queries, request *sospost.UpdateSOSPostRequest, -) *pnd.AppError { +) error { if err := service.DeleteLinkSOSPostDates(ctx, q, request.ID); err != nil { return err } @@ -398,24 +398,24 @@ func (service *SOSPostService) updateAllLinks( func (service *SOSPostService) CheckUpdatePermission( ctx context.Context, fbUID string, sosPostID uuid.UUID, -) (bool, *pnd.AppError) { +) (bool, error) { tx, err := service.conn.BeginTx(ctx) defer tx.Rollback() if err != nil { return false, err } - userData, err2 := databasegen.New(tx).FindUser(ctx, databasegen.FindUserParams{ + userData, err := databasegen.New(tx).FindUser(ctx, databasegen.FindUserParams{ FbUid: utils.StrToNullStr(fbUID), }) - if err2 != nil { - return false, pnd.FromPostgresError(err2) + if err != nil { + return false, pnd.FromPostgresError(err) } - sosPost, err2 := databasegen.New(tx). + sosPost, err := databasegen.New(tx). FindSOSPostByID(ctx, uuid.NullUUID{UUID: sosPostID, Valid: true}) - if err2 != nil { - return false, pnd.FromPostgresError(err2) + if err != nil { + return false, pnd.FromPostgresError(err) } sosPostInfo := sospost.ToInfoFromFindByIDRow(sosPost) @@ -428,7 +428,7 @@ func (service *SOSPostService) CheckUpdatePermission( func (service *SOSPostService) SaveSOSDates( ctx context.Context, tx *databasegen.Queries, dates []sospost.SOSDateView, sosPostID uuid.UUID, -) *pnd.AppError { +) error { for _, date := range dates { dateStartAt, err := utils.StrToNullTime(date.DateStartAt) if err != nil { @@ -439,22 +439,21 @@ func (service *SOSPostService) SaveSOSDates( return err } - d, err2 := databasegen.New(service.conn).InsertSOSDate(ctx, databasegen.InsertSOSDateParams{ + d, err := databasegen.New(service.conn).InsertSOSDate(ctx, databasegen.InsertSOSDateParams{ ID: datatype.NewUUIDV7(), DateStartAt: dateStartAt, DateEndAt: dateEndAt, }) - if err2 != nil { - return pnd.FromPostgresError(err2) + if err != nil { + return pnd.FromPostgresError(err) } - err3 := tx.LinkSOSPostDate(ctx, databasegen.LinkSOSPostDateParams{ + if err := tx.LinkSOSPostDate(ctx, databasegen.LinkSOSPostDateParams{ ID: datatype.NewUUIDV7(), SosPostID: sosPostID, SosDatesID: d.ID, - }) - if err3 != nil { - return pnd.FromPostgresError(err3) + }); err != nil { + return pnd.FromPostgresError(err) } } return nil @@ -462,16 +461,16 @@ func (service *SOSPostService) SaveSOSDates( func (service *SOSPostService) SaveLinkSOSPostImage( ctx context.Context, tx *databasegen.Queries, imageIDs []uuid.UUID, sosPostID uuid.UUID, -) *pnd.AppError { +) error { for _, mediaID := range imageIDs { log.Default().Println("mediaID", mediaID) - err := tx.LinkResourceMedia(ctx, databasegen.LinkResourceMediaParams{ + + if err := tx.LinkResourceMedia(ctx, databasegen.LinkResourceMediaParams{ ID: datatype.NewUUIDV7(), MediaID: mediaID, ResourceID: sosPostID, ResourceType: utils.StrToNullStr(resourcemedia.SOSResourceType.String()), - }) - if err != nil { + }); err != nil { return pnd.FromPostgresError(err) } } @@ -480,15 +479,15 @@ func (service *SOSPostService) SaveLinkSOSPostImage( func (service *SOSPostService) SaveLinkConditions( ctx context.Context, tx *databasegen.Queries, conditionIDs []uuid.UUID, sosPostID uuid.UUID, -) *pnd.AppError { +) error { for _, conditionID := range conditionIDs { log.Default().Println("conditionID", conditionID) - err := tx.LinkSOSPostCondition(ctx, databasegen.LinkSOSPostConditionParams{ + + if err := tx.LinkSOSPostCondition(ctx, databasegen.LinkSOSPostConditionParams{ ID: datatype.NewUUIDV7(), SosPostID: sosPostID, SosConditionID: uuid.NullUUID{UUID: conditionID, Valid: true}, - }) - if err != nil { + }); err != nil { return pnd.FromPostgresError(err) } } @@ -497,15 +496,15 @@ func (service *SOSPostService) SaveLinkConditions( func (service *SOSPostService) SaveLinkPets( ctx context.Context, tx *databasegen.Queries, petIDs []uuid.UUID, sosPostID uuid.UUID, -) *pnd.AppError { +) error { for _, petID := range petIDs { log.Default().Println("petID", petID) - err := tx.LinkSOSPostPet(ctx, databasegen.LinkSOSPostPetParams{ + + if err := tx.LinkSOSPostPet(ctx, databasegen.LinkSOSPostPetParams{ ID: datatype.NewUUIDV7(), SosPostID: sosPostID, PetID: petID, - }) - if err != nil { + }); err != nil { return pnd.FromPostgresError(err) } } @@ -514,9 +513,8 @@ func (service *SOSPostService) SaveLinkPets( func (service *SOSPostService) DeleteLinkSOSPostDates( ctx context.Context, tx *databasegen.Queries, sosPostID uuid.UUID, -) *pnd.AppError { - err := tx.DeleteSOSPostDateBySOSPostID(ctx, sosPostID) - if err != nil { +) error { + if err := tx.DeleteSOSPostDateBySOSPostID(ctx, sosPostID); err != nil { return pnd.FromPostgresError(err) } return nil @@ -524,9 +522,8 @@ func (service *SOSPostService) DeleteLinkSOSPostDates( func (service *SOSPostService) DeleteLinkSOSPostImages( ctx context.Context, tx *databasegen.Queries, sosPostID uuid.UUID, -) *pnd.AppError { - err := tx.DeleteResourceMediaByResourceID(ctx, sosPostID) - if err != nil { +) error { + if err := tx.DeleteResourceMediaByResourceID(ctx, sosPostID); err != nil { return pnd.FromPostgresError(err) } return nil @@ -534,9 +531,8 @@ func (service *SOSPostService) DeleteLinkSOSPostImages( func (service *SOSPostService) DeleteLinkSOSPostConditions( ctx context.Context, tx *databasegen.Queries, sosPostID uuid.UUID, -) *pnd.AppError { - err := tx.DeleteSOSPostConditionBySOSPostID(ctx, sosPostID) - if err != nil { +) error { + if err := tx.DeleteSOSPostConditionBySOSPostID(ctx, sosPostID); err != nil { return pnd.FromPostgresError(err) } return nil @@ -544,9 +540,8 @@ func (service *SOSPostService) DeleteLinkSOSPostConditions( func (service *SOSPostService) DeleteLinkSOSPostPets( ctx context.Context, tx *databasegen.Queries, sosPostID uuid.UUID, -) *pnd.AppError { - err := tx.DeleteSOSPostPetBySOSPostID(ctx, sosPostID) - if err != nil { +) error { + if err := tx.DeleteSOSPostPetBySOSPostID(ctx, sosPostID); err != nil { return pnd.FromPostgresError(err) } return nil diff --git a/internal/service/tests/sos_post_service_test.go b/internal/service/tests/sos_post_service_test.go index dc92b41d..e3df2741 100644 --- a/internal/service/tests/sos_post_service_test.go +++ b/internal/service/tests/sos_post_service_test.go @@ -22,8 +22,8 @@ func setUp(ctx context.Context, t *testing.T) (*database.DB, func(t *testing.T)) db, tearDown := tests.SetUp(t) conditionService := service.NewSOSConditionService(db) - if _, err2 := conditionService.InitConditions(ctx); err2 != nil { - t.Errorf("InitConditions failed: %v", err2) + if _, err := conditionService.InitConditions(ctx); err != nil { + t.Errorf("InitConditions failed: %v", err) } return db, tearDown @@ -230,7 +230,7 @@ func TestFindSOSPosts(t *testing.T) { i, conditionIDs, ) - sosPostService.WriteSOSPost(ctx, uid, request) + _, _ = sosPostService.WriteSOSPost(ctx, uid, request) sosPostRequests = append(sosPostRequests, *request) } @@ -299,7 +299,7 @@ func TestFindSOSPosts(t *testing.T) { i, conditionIDs, ) - sosPostService.WriteSOSPost(ctx, uid, request) + _, _ = sosPostService.WriteSOSPost(ctx, uid, request) writeRequests = append(writeRequests, *request) } @@ -310,7 +310,7 @@ func TestFindSOSPosts(t *testing.T) { 3, conditionIDs, ) - sosPostService.WriteSOSPost(ctx, uid, request) + _, _ = sosPostService.WriteSOSPost(ctx, uid, request) writeRequests = append(writeRequests, *request) // 강아지, 고양이인 경우 @@ -320,7 +320,7 @@ func TestFindSOSPosts(t *testing.T) { 4, conditionIDs, ) - sosPostService.WriteSOSPost(ctx, uid, request) + _, _ = sosPostService.WriteSOSPost(ctx, uid, request) writeRequests = append(writeRequests, *request) // when @@ -388,7 +388,7 @@ func TestFindSOSPosts(t *testing.T) { i, conditionIDs, ) - sosPostService.WriteSOSPost(ctx, owner.FirebaseUID, request) + _, _ = sosPostService.WriteSOSPost(ctx, owner.FirebaseUID, request) writeRequests = append(writeRequests, *request) } diff --git a/internal/service/tests/user_service_test.go b/internal/service/tests/user_service_test.go index 993b1f2a..80fc4ad8 100644 --- a/internal/service/tests/user_service_test.go +++ b/internal/service/tests/user_service_test.go @@ -77,7 +77,7 @@ func TestRegisterUser(t *testing.T) { userRequest := tests.NewDummyRegisterUserRequest( uuid.NullUUID{UUID: profileImage.ID, Valid: true}, ) - userService.RegisterUser(ctx, userRequest) + _, _ = userService.RegisterUser(ctx, userRequest) // When _, err := userService.RegisterUser(ctx, userRequest) @@ -108,9 +108,9 @@ func TestFindUsers(t *testing.T) { FirebaseUID: "uid", } - userService.RegisterUser(ctx, targetUserRequest) + _, _ = userService.RegisterUser(ctx, targetUserRequest) for i := 0; i < 2; i++ { - userService.RegisterUser(ctx, &user.RegisterUserRequest{ + _, _ = userService.RegisterUser(ctx, &user.RegisterUserRequest{ Email: fmt.Sprintf("test%d@example.com", i), Nickname: fmt.Sprintf("nickname%d", i), Fullname: fmt.Sprintf("fullname%d", i), @@ -246,7 +246,7 @@ func TestExistsByEmail(t *testing.T) { userRequest := tests.NewDummyRegisterUserRequest( uuid.NullUUID{UUID: profileImage.ID, Valid: true}, ) - userService.RegisterUser(ctx, userRequest) + _, _ = userService.RegisterUser(ctx, userRequest) // When exists, _ := userService.ExistsByNickname(ctx, userRequest.Nickname) @@ -279,7 +279,7 @@ func TestUpdateUserByUID(t *testing.T) { media.TypeImage, "updated_profile_image.jpg", ) - userService.UpdateUserByUID( + _, _ = userService.UpdateUserByUID( ctx, targetUser.FirebaseUID, updatedNickname, @@ -461,7 +461,7 @@ func TestDeletePet(t *testing.T) { createdPet := createdPets.Pets[0] // When - userService.DeletePet(ctx, registeredUser.FirebaseUID, createdPet.ID) + _ = userService.DeletePet(ctx, registeredUser.FirebaseUID, createdPet.ID) // Then found, _ := userService.FindPets(ctx, pet.FindPetsParams{ diff --git a/internal/service/user_service.go b/internal/service/user_service.go index eda42f6e..67c72910 100644 --- a/internal/service/user_service.go +++ b/internal/service/user_service.go @@ -30,7 +30,7 @@ func NewUserService(conn *database.DB, mediaService *MediaService) *UserService func (service *UserService) RegisterUser( ctx context.Context, registerUserRequest *user.RegisterUserRequest, -) (*user.InternalView, *pnd.AppError) { +) (*user.InternalView, error) { if registerUserRequest.ProfileImageID.Valid { _, err := service.mediaService.FindMediaByID(ctx, registerUserRequest.ProfileImageID.UUID) if err != nil { @@ -44,22 +44,22 @@ func (service *UserService) RegisterUser( return nil, err } - _, err2 := databasegen.New(service.conn). + _, err = databasegen.New(service.conn). WithTx(tx.Tx). CreateUser(ctx, registerUserRequest.ToDBParams()) - if err2 != nil { - return nil, pnd.FromPostgresError(err2) + if err != nil { + return nil, pnd.FromPostgresError(err) } if err := tx.Commit(); err != nil { return nil, err } - row, err2 := databasegen.New(service.conn).FindUser(ctx, databasegen.FindUserParams{ + row, err := databasegen.New(service.conn).FindUser(ctx, databasegen.FindUserParams{ FbUid: utils.StrToNullStr(registerUserRequest.FirebaseUID), }) - if err2 != nil { - return nil, pnd.FromPostgresError(err2) + if err != nil { + return nil, pnd.FromPostgresError(err) } return user.ToWithProfileImage(row).ToInternalView(), nil @@ -67,7 +67,7 @@ func (service *UserService) RegisterUser( func (service *UserService) FindUsers( ctx context.Context, params user.FindUsersParams, -) (*user.ListWithoutPrivateInfo, *pnd.AppError) { +) (*user.ListWithoutPrivateInfo, error) { rows, err := databasegen.New(service.conn).FindUsers(ctx, params.ToDBParams()) if err != nil { return nil, pnd.FromPostgresError(err) @@ -79,7 +79,7 @@ func (service *UserService) FindUsers( func (service *UserService) FindUser( ctx context.Context, params user.FindUserParams, -) (*user.WithProfileImage, *pnd.AppError) { +) (*user.WithProfileImage, error) { row, err := databasegen.New(service.conn).FindUser(ctx, params.ToDBParams()) if err != nil { return nil, pnd.FromPostgresError(err) @@ -90,16 +90,16 @@ func (service *UserService) FindUser( func (service *UserService) FindUserProfile( ctx context.Context, params user.FindUserParams, -) (*user.ProfileView, *pnd.AppError) { +) (*user.ProfileView, error) { row, err := databasegen.New(service.conn).FindUser(ctx, params.ToDBParams()) if err != nil { return nil, pnd.FromPostgresError(err) } petParams := pet.FindPetsParams{OwnerID: uuid.NullUUID{UUID: row.ID, Valid: true}} - pets, err2 := service.FindPets(ctx, petParams) - if err2 != nil { - return nil, err2 + pets, err := service.FindPets(ctx, petParams) + if err != nil { + return nil, err } return user.NewProfileView(row, pets), nil @@ -108,7 +108,7 @@ func (service *UserService) FindUserProfile( func (service *UserService) ExistsByNickname( ctx context.Context, nickname string, -) (bool, *pnd.AppError) { +) (bool, error) { existsByNickname, err := databasegen.New(service.conn).ExistsUserByNickname(ctx, nickname) if err != nil { return existsByNickname, pnd.FromPostgresError(err) @@ -119,39 +119,39 @@ func (service *UserService) ExistsByNickname( func (service *UserService) UpdateUserByUID( ctx context.Context, uid, nickname string, profileImageID uuid.NullUUID, -) (*user.MyProfileView, *pnd.AppError) { +) (*user.MyProfileView, error) { tx, err := service.conn.BeginTx(ctx) defer tx.Rollback() if err != nil { return nil, err } - _, err2 := databasegen.New(service.conn). + _, err = databasegen.New(service.conn). WithTx(tx.Tx). UpdateUserByFbUID(ctx, databasegen.UpdateUserByFbUIDParams{ Nickname: nickname, ProfileImageID: profileImageID, FbUid: utils.StrToNullStr(uid), }) - if err2 != nil { - return nil, pnd.FromPostgresError(err2) + if err != nil { + return nil, pnd.FromPostgresError(err) } if err := tx.Commit(); err != nil { return nil, err } - refreshedUser, err2 := databasegen.New(service.conn).FindUser(ctx, databasegen.FindUserParams{ + refreshedUser, err := databasegen.New(service.conn).FindUser(ctx, databasegen.FindUserParams{ FbUid: utils.StrToNullStr(uid), }) - if err2 != nil { - return nil, pnd.FromPostgresError(err2) + if err != nil { + return nil, pnd.FromPostgresError(err) } return user.ToWithProfileImage(refreshedUser).ToMyProfileView(), nil } -func (service *UserService) DeleteUserByUID(ctx context.Context, uid string) *pnd.AppError { +func (service *UserService) DeleteUserByUID(ctx context.Context, uid string) error { tx, err := service.conn.BeginTx(ctx) defer tx.Rollback() if err != nil { @@ -167,7 +167,7 @@ func (service *UserService) DeleteUserByUID(ctx context.Context, uid string) *pn func (service *UserService) FindPet( ctx context.Context, params pet.FindPetParams, -) (*pet.WithProfileImage, *pnd.AppError) { +) (*pet.WithProfileImage, error) { row, err := databasegen.New(service.conn).FindPet(ctx, params.ToDBParams()) if err != nil { return nil, pnd.FromPostgresError(err) @@ -179,7 +179,7 @@ func (service *UserService) FindPet( func (service *UserService) FindPets( ctx context.Context, params pet.FindPetsParams, -) (*pet.ListView, *pnd.AppError) { +) (*pet.ListView, error) { rows, err := databasegen.New(service.conn).FindPets(ctx, params.ToDBParams()) if err != nil { return nil, pnd.FromPostgresError(err) @@ -190,7 +190,7 @@ func (service *UserService) FindPets( func (service *UserService) AddPetsToOwner( ctx context.Context, uid string, addPetsRequest pet.AddPetsToOwnerRequest, -) (*pet.ListView, *pnd.AppError) { +) (*pet.ListView, error) { tx, err := service.conn.BeginTx(ctx) defer tx.Rollback() if err != nil { @@ -198,11 +198,11 @@ func (service *UserService) AddPetsToOwner( } // 사용자가 존재하는지 확인 - userData, err2 := databasegen.New(service.conn).FindUser(ctx, databasegen.FindUserParams{ + userData, err := databasegen.New(service.conn).FindUser(ctx, databasegen.FindUserParams{ FbUid: utils.StrToNullStr(uid), }) - if err2 != nil { - return nil, pnd.FromPostgresError(err2) + if err != nil { + return nil, pnd.FromPostgresError(err) } // 프로필 이미지 ID가 DB에 존재하는지 확인 @@ -248,11 +248,11 @@ func (service *UserService) AddPetsToOwner( return nil, err } - rows, err2 := databasegen.New(service.conn).FindPetsByIDs(ctx, databasegen.FindPetsByIDsParams{ + rows, err := databasegen.New(service.conn).FindPetsByIDs(ctx, databasegen.FindPetsByIDsParams{ Ids: petIDs, }) - if err2 != nil { - return nil, pnd.FromPostgresError(err2) + if err != nil { + return nil, pnd.FromPostgresError(err) } return pet.ToListViewFromIDsRows(rows), nil @@ -260,7 +260,7 @@ func (service *UserService) AddPetsToOwner( func (service *UserService) UpdatePet( ctx context.Context, uid string, petID uuid.UUID, updatePetRequest pet.UpdatePetRequest, -) (*pet.DetailView, *pnd.AppError) { +) (*pet.DetailView, error) { owner, err := service.FindUser(ctx, user.FindUserParams{FbUID: &uid, IncludeDeleted: false}) if err != nil { return nil, err @@ -290,8 +290,8 @@ func (service *UserService) UpdatePet( return nil, err } - birthDate, err2 := datatype.ParseDateToTime(updatePetRequest.BirthDate) - if err2 != nil { + birthDate, err := datatype.ParseDateToTime(updatePetRequest.BirthDate) + if err != nil { return nil, pnd.ErrInvalidBody(fmt.Errorf("잘못된 생년월일 형식입니다. %s", updatePetRequest.BirthDate)) } @@ -326,7 +326,7 @@ func (service *UserService) DeletePet( ctx context.Context, uid string, petID uuid.UUID, -) *pnd.AppError { +) error { owner, err := service.FindUser(ctx, user.FindUserParams{FbUID: &uid}) if err != nil { return err diff --git a/internal/tests/service.go b/internal/tests/service.go index 8a792562..6e9dca89 100644 --- a/internal/tests/service.go +++ b/internal/tests/service.go @@ -11,7 +11,6 @@ import ( "github.com/pet-sitter/pets-next-door-api/internal/infra/database" - pnd "github.com/pet-sitter/pets-next-door-api/api" bucketinfra "github.com/pet-sitter/pets-next-door-api/internal/infra/bucket" "github.com/pet-sitter/pets-next-door-api/internal/domain/pet" @@ -23,7 +22,7 @@ type StubUploader struct{} func (u StubUploader) UploadFile( _ io.ReadSeeker, fileName string, -) (url string, appError *pnd.AppError) { +) (string, error) { return "https://example.com/files/" + fileName, nil } diff --git a/internal/wschat/server.go b/internal/wschat/server.go index a8433052..7436d137 100644 --- a/internal/wschat/server.go +++ b/internal/wschat/server.go @@ -56,20 +56,20 @@ func (s *WSServer) HandleConnections( ) error { log.Info().Msg("Handling connections") - foundUser, err2 := s.authService.VerifyAuthAndGetUser( + foundUser, err := s.authService.VerifyAuthAndGetUser( c.Request().Context(), c.Request().Header.Get("Authorization"), ) - if err2 != nil { - return c.JSON(err2.StatusCode, err2) + if err != nil { + return err } userID := foundUser.ID conn, err := s.upgrader.Upgrade(c.Response().Writer, c.Request(), nil) defer func() { - err2 := conn.Close() - if err2 != nil { - log.Error().Err(err2).Msg("Failed to close connection") + err := conn.Close() + if err != nil { + log.Error().Err(err).Msg("Failed to close connection") } delete(s.clients, userID) }() @@ -145,7 +145,7 @@ func (s *WSServer) LoopOverClientMessages() { } medias, err := s.mediaService.FindMediasByIDs(ctx, ids) if err != nil { - log.Error().Err(err.Err).Msg("Failed to find media") + log.Error().Err(err).Msg("Failed to find media") msg = NewErrorMessageResponse(msgReq.MessageID, msgReq.Sender, msgReq.Room, "Failed to find media", time.Now()) } else { msg = NewMediaMessageResponse(msgReq.MessageID, msgReq.Sender, msgReq.Room, medias, time.Now())