Skip to content

Commit

Permalink
Merge pull request #13 from codermuss/ft/categories
Browse files Browse the repository at this point in the history
✨ add categories api and  api tests
  • Loading branch information
codermuss authored Jul 28, 2024
2 parents de35721 + 0cf53ae commit 1cd432c
Show file tree
Hide file tree
Showing 10 changed files with 184 additions and 3 deletions.
27 changes: 27 additions & 0 deletions api/category.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package api

import (
"net/http"

"github.com/gin-gonic/gin"
)

func (server *Server) GetCategories(ctx *gin.Context) {

categories, err := server.store.GetCategories(ctx)
if err != nil {
BuildResponse(ctx, BaseResponse{
Code: http.StatusInternalServerError,
Message: ResponseMessage{
Type: ERROR,
Content: "Internal error: " + err.Error(),
},
})
return
}

BuildResponse(ctx, BaseResponse{
Code: http.StatusOK,
Data: categories,
})
}
104 changes: 104 additions & 0 deletions api/category_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
package api

import (
"bytes"
"database/sql"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"testing"
"time"

"github.com/golang/mock/gomock"
mockdb "github.com/mustafayilmazdev/musarchive/db/mock"
db "github.com/mustafayilmazdev/musarchive/db/sqlc"
"github.com/mustafayilmazdev/musarchive/token"
"github.com/stretchr/testify/require"
)

func TestGetCategories(t *testing.T) {
user, _ := RandomUser(t)

categories := []db.Category{
{ID: 1, Name: "Category 1"},
{ID: 2, Name: "Category 2"},
}

testCases := []struct {
name string
setupAuth func(t *testing.T, request *http.Request, tokenMaker token.Maker)
buildStubs func(store *mockdb.MockStore)
checkResponse func(recorder *httptest.ResponseRecorder)
}{
{
name: "OK",
setupAuth: func(t *testing.T, request *http.Request, tokenMaker token.Maker) {
addAuthorization(t, request, tokenMaker, authorizationTypeBearer, int(user.ID), user.Role, time.Minute)
},
buildStubs: func(store *mockdb.MockStore) {
store.EXPECT().
GetCategories(gomock.Any()).
Times(1).
Return(categories, nil)
},
checkResponse: func(recorder *httptest.ResponseRecorder) {
require.Equal(t, http.StatusOK, recorder.Code)
requireBodyMatchCategories(t, recorder.Body, categories)
},
},
{
name: "InternalError",
setupAuth: func(t *testing.T, request *http.Request, tokenMaker token.Maker) {
addAuthorization(t, request, tokenMaker, authorizationTypeBearer, int(user.ID), user.Role, time.Minute)
},
buildStubs: func(store *mockdb.MockStore) {
store.EXPECT().
GetCategories(gomock.Any()).
Times(1).Return([]db.Category{}, sql.ErrConnDone)
},
checkResponse: func(recorder *httptest.ResponseRecorder) {
require.Equal(t, http.StatusInternalServerError, recorder.Code)
},
},
}

for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()

store := mockdb.NewMockStore(ctrl)
tc.buildStubs(store)

server := newTestServer(t, store)
recorder := httptest.NewRecorder()

url := "/v1/categories/index"
request, err := http.NewRequest(http.MethodGet, url, nil)
require.NoError(t, err)

tc.setupAuth(t, request, server.tokenMaker)
server.Router.ServeHTTP(recorder, request)
tc.checkResponse(recorder)
})
}
}

func requireBodyMatchCategories(t *testing.T, body *bytes.Buffer, categories []db.Category) {
data, err := io.ReadAll(body)
require.NoError(t, err)

var response BaseResponse
err = json.Unmarshal(data, &response)
require.NoError(t, err)
require.Equal(t, http.StatusOK, response.Code)

categoriesJSON, err := json.Marshal(categories)
require.NoError(t, err)

responseDataJSON, err := json.Marshal(response.Data)
require.NoError(t, err)

require.JSONEq(t, string(categoriesJSON), string(responseDataJSON))
}
2 changes: 1 addition & 1 deletion api/login_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ func TestLoginUserAPI(t *testing.T) {
data, err := json.Marshal(tc.body)
require.NoError(t, err)

url := "/v1/login"
url := "/v1/auth/login"
request, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(data))
require.NoError(t, err)

Expand Down
2 changes: 1 addition & 1 deletion api/post_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -309,7 +309,7 @@ func TestGetPostsAPI(t *testing.T) {
data, err := json.Marshal(tc.body)
require.NoError(t, err)

url := "/v1/posts"
url := "/v1/posts/index"
request, err := http.NewRequest(http.MethodGet, url, bytes.NewReader(data))
require.NoError(t, err)

Expand Down
2 changes: 1 addition & 1 deletion api/register_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ func TestCreateUserAPI(t *testing.T) {
data, err := json.Marshal(tc.body)
require.NoError(t, err)

url := "/v1/register"
url := "/v1/auth/register"
request, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(data))
require.NoError(t, err)

Expand Down
4 changes: 4 additions & 0 deletions api/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,10 @@ func (server *Server) setupRouter() {
postRoutes.GET("/followed", server.GetFollowedPosts)
postRoutes.POST("/create", server.CreatePost)
}
categoryRoutes := router.Group("/v1/categories").Use(authMiddleware(server.tokenMaker))
{
categoryRoutes.GET("/index", server.GetCategories)
}

// Serve the bundled static files
statikFS, err := fs.New()
Expand Down
15 changes: 15 additions & 0 deletions db/mock/store.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions db/query/categories.sql
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,11 @@ SELECT id, name
FROM categories
WHERE id = $1;


-- name: GetCategories :many
SELECT id, name
FROM categories;

-- name: UpdateCategory :one
UPDATE categories
SET name = $1
Expand Down
25 changes: 25 additions & 0 deletions db/sqlc/categories.sql.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions db/sqlc/querier.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 1cd432c

Please sign in to comment.