-
Notifications
You must be signed in to change notification settings - Fork 0
Add Create Product Handler #43
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
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
9d36439
Combine `created_at` and `updated_at` into a single `timestamp` field…
jlpdeveloper da4f1c7
Add `CreateProduct` handler with tests, mock implementation, and rout…
jlpdeveloper f99cd05
Add validation for `Name` and `PlatformID` in `CreateProduct` handler…
jlpdeveloper cb7c5c0
Refactor `CreateProduct` handler to use `CreateProductRequest` struct…
jlpdeveloper 9bd78fb
Add error handling for `json.Marshal` in `product_test.go` to prevent…
jlpdeveloper 5dfe2b9
Add error handling for HTTP response writes in `structured_logger_tes…
jlpdeveloper File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,52 @@ | ||
| package productHandler | ||
|
|
||
| import ( | ||
| "context" | ||
| "encoding/json" | ||
| "net/http" | ||
| "products/internal/db/product" | ||
| "time" | ||
|
|
||
| "github.com/jackc/pgx/v5/pgtype" | ||
| ) | ||
|
|
||
| type CreateProductRequest struct { | ||
| Name string `json:"name"` | ||
| PlatformID int32 `json:"platform_id"` | ||
| Description string `json:"description"` | ||
| } | ||
|
|
||
| func (h *ProductHandler) CreateProduct(w http.ResponseWriter, r *http.Request) { | ||
| var req CreateProductRequest | ||
| if err := json.NewDecoder(r.Body).Decode(&req); err != nil { | ||
| http.Error(w, "Invalid request body", http.StatusBadRequest) | ||
| return | ||
| } | ||
| if req.Name == "" || req.PlatformID == 0 { | ||
| http.Error(w, "Name and platform ID are required", http.StatusBadRequest) | ||
| return | ||
| } | ||
|
|
||
| params := product.CreateProductParams{ | ||
| Name: req.Name, | ||
| PlatformID: req.PlatformID, | ||
| Description: pgtype.Text{ | ||
| Valid: req.Description != "", | ||
| String: req.Description, | ||
| }, | ||
| Timestamp: pgtype.Timestamptz{ | ||
| Valid: true, | ||
| Time: time.Now().UTC(), | ||
| }, | ||
| } | ||
|
|
||
| contextWithTimeOut, cancel := context.WithTimeout(r.Context(), 5*time.Second) | ||
| defer cancel() | ||
| if err := h.queries.CreateProduct(contextWithTimeOut, params); err != nil { | ||
| http.Error(w, "Failed to create product", http.StatusInternalServerError) | ||
| return | ||
| } | ||
|
|
||
| w.WriteHeader(http.StatusCreated) | ||
|
|
||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,132 @@ | ||
| package productHandler | ||
|
|
||
| import ( | ||
| "bytes" | ||
| "context" | ||
| "encoding/json" | ||
| "errors" | ||
| "net/http" | ||
| "net/http/httptest" | ||
| "products/internal/db/product" | ||
| "testing" | ||
| ) | ||
|
|
||
| type mockProductQuerier struct { | ||
| createProductFunc func(ctx context.Context, arg product.CreateProductParams) error | ||
| deleteProductFunc func(ctx context.Context, id int32) error | ||
| getProductByIdFunc func(ctx context.Context, id int32) (product.Product, error) | ||
| getProductsByPlatformFunc func(ctx context.Context, platformID int32) ([]product.Product, error) | ||
| updateProductFunc func(ctx context.Context, arg product.UpdateProductParams) error | ||
| } | ||
|
|
||
| func (m *mockProductQuerier) CreateProduct(ctx context.Context, arg product.CreateProductParams) error { | ||
| return m.createProductFunc(ctx, arg) | ||
| } | ||
|
|
||
| func (m *mockProductQuerier) DeleteProduct(ctx context.Context, id int32) error { | ||
| return m.deleteProductFunc(ctx, id) | ||
| } | ||
|
|
||
| func (m *mockProductQuerier) GetProductById(ctx context.Context, id int32) (product.Product, error) { | ||
| return m.getProductByIdFunc(ctx, id) | ||
| } | ||
|
|
||
| func (m *mockProductQuerier) GetProductsByPlatform(ctx context.Context, platformID int32) ([]product.Product, error) { | ||
| return m.getProductsByPlatformFunc(ctx, platformID) | ||
| } | ||
|
|
||
| func (m *mockProductQuerier) UpdateProduct(ctx context.Context, arg product.UpdateProductParams) error { | ||
| return m.updateProductFunc(ctx, arg) | ||
| } | ||
|
|
||
| func TestCreateProduct(t *testing.T) { | ||
| tests := []struct { | ||
| name string | ||
| requestBody any | ||
| mockSetup func(m *mockProductQuerier) | ||
| expectedStatus int | ||
| }{ | ||
| { | ||
| name: "Success", | ||
| requestBody: CreateProductRequest{ | ||
| PlatformID: 1, | ||
| Name: "Test Product", | ||
| }, | ||
| mockSetup: func(m *mockProductQuerier) { | ||
| m.createProductFunc = func(ctx context.Context, arg product.CreateProductParams) error { | ||
| if arg.Name != "Test Product" { | ||
| return errors.New("unexpected name") | ||
| } | ||
| if arg.PlatformID != 1 { | ||
| return errors.New("unexpected platform id") | ||
| } | ||
| return nil | ||
| } | ||
| }, | ||
| expectedStatus: http.StatusCreated, | ||
| }, | ||
| { | ||
| name: "Invalid JSON", | ||
| requestBody: "invalid json", | ||
| mockSetup: func(m *mockProductQuerier) {}, | ||
| expectedStatus: http.StatusBadRequest, | ||
| }, | ||
| { | ||
| name: "DB Failure", | ||
| requestBody: CreateProductRequest{ | ||
| PlatformID: 1, | ||
| Name: "Fail Product", | ||
| }, | ||
| mockSetup: func(m *mockProductQuerier) { | ||
| m.createProductFunc = func(ctx context.Context, arg product.CreateProductParams) error { | ||
| return errors.New("db error") | ||
| } | ||
| }, | ||
| expectedStatus: http.StatusInternalServerError, | ||
| }, | ||
| { | ||
| name: "Missing Name", | ||
| requestBody: CreateProductRequest{ | ||
| PlatformID: 1, | ||
| }, | ||
| mockSetup: func(m *mockProductQuerier) {}, | ||
| expectedStatus: http.StatusBadRequest, | ||
| }, | ||
| { | ||
| name: "Missing PlatformID", | ||
| requestBody: CreateProductRequest{ | ||
| Name: "Test Product", | ||
| }, | ||
| mockSetup: func(m *mockProductQuerier) {}, | ||
| expectedStatus: http.StatusBadRequest, | ||
| }, | ||
| } | ||
|
|
||
| for _, tt := range tests { | ||
| t.Run(tt.name, func(t *testing.T) { | ||
| mock := &mockProductQuerier{} | ||
| tt.mockSetup(mock) | ||
| h := NewProductHandler(mock) | ||
|
|
||
| var body []byte | ||
| if s, ok := tt.requestBody.(string); ok { | ||
| body = []byte(s) | ||
| } else { | ||
| var err error | ||
| body, err = json.Marshal(tt.requestBody) | ||
| if err != nil { | ||
| t.Fatalf("json.Marshal requestBody failed: %v", err) | ||
| } | ||
| } | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
|
|
||
| req := httptest.NewRequest(http.MethodPost, "/products", bytes.NewBuffer(body)) | ||
| rr := httptest.NewRecorder() | ||
|
|
||
| h.CreateProduct(rr, req) | ||
|
|
||
| if rr.Code != tt.expectedStatus { | ||
| t.Errorf("expected status %v, got %v", tt.expectedStatus, rr.Code) | ||
| } | ||
| }) | ||
| } | ||
| } | ||
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.