-
Notifications
You must be signed in to change notification settings - Fork 50
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #65 from Ajinx1/ayotee-dev
NewsLetter Page Api Endpoint
- Loading branch information
Showing
10 changed files
with
301 additions
and
2 deletions.
There are no files selected for viewing
This file contains 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 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,36 @@ | ||
package models | ||
|
||
import ( | ||
"time" | ||
|
||
"github.com/hngprojects/hng_boilerplate_golang_web/pkg/repository/storage/postgresql" | ||
"github.com/hngprojects/hng_boilerplate_golang_web/utility" | ||
"gorm.io/gorm" | ||
) | ||
|
||
type NewsLetter struct { | ||
ID string `gorm:"primaryKey;type:uuid" json:"id"` | ||
Email string `gorm:"unique;not null" json:"email" validate:"required,email"` | ||
CreatedAt time.Time `json:"created_at"` | ||
UpdatedAt time.Time `json:"updated_at"` | ||
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"` | ||
} | ||
|
||
func (n *NewsLetter) BeforeCreate(tx *gorm.DB) (err error) { | ||
|
||
if n.ID == "" { | ||
n.ID = utility.GenerateUUID() | ||
} | ||
return | ||
} | ||
|
||
func (c *NewsLetter) CreateNewsLetter(db *gorm.DB) error { | ||
|
||
err := postgresql.CreateOneRecord(db, &c) | ||
|
||
if err != nil { | ||
return err | ||
} | ||
|
||
return nil | ||
} |
This file contains 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,59 @@ | ||
package newsletter | ||
|
||
import ( | ||
"net/http" | ||
|
||
"github.com/gin-gonic/gin" | ||
"github.com/go-playground/validator/v10" | ||
"github.com/hngprojects/hng_boilerplate_golang_web/external/request" | ||
"github.com/hngprojects/hng_boilerplate_golang_web/internal/models" | ||
"github.com/hngprojects/hng_boilerplate_golang_web/pkg/repository/storage" | ||
service "github.com/hngprojects/hng_boilerplate_golang_web/services/newsletter" | ||
"github.com/hngprojects/hng_boilerplate_golang_web/utility" | ||
) | ||
|
||
type Controller struct { | ||
Db *storage.Database | ||
Validator *validator.Validate | ||
Logger *utility.Logger | ||
ExtReq request.ExternalRequest | ||
} | ||
|
||
func (base *Controller) SubscribeNewsLetter(c *gin.Context) { | ||
var ( | ||
req = models.NewsLetter{} | ||
) | ||
|
||
err := c.ShouldBind(&req) | ||
if err != nil { | ||
rd := utility.BuildErrorResponse(http.StatusBadRequest, "error", "Failed to parse request body", err, nil) | ||
c.JSON(http.StatusBadRequest, rd) | ||
return | ||
} | ||
|
||
err = base.Validator.Struct(&req) | ||
if err != nil { | ||
rd := utility.BuildErrorResponse(http.StatusUnprocessableEntity, "error", "Validation failed", | ||
utility.ValidationResponse(err, base.Validator), nil) | ||
c.JSON(http.StatusUnprocessableEntity, rd) | ||
return | ||
} | ||
|
||
err = service.NewsLetterSubscribe(&req, base.Db.Postgresql) | ||
if err != nil { | ||
if err == service.ErrEmailAlreadySubscribed { | ||
rd := utility.BuildErrorResponse(http.StatusConflict, "error", "Email already subscribed", nil, nil) | ||
c.JSON(http.StatusConflict, rd) | ||
} else { | ||
rd := utility.BuildErrorResponse(http.StatusInternalServerError, "error", "Failed to subscribe", err, nil) | ||
c.JSON(http.StatusInternalServerError, rd) | ||
} | ||
return | ||
} | ||
|
||
base.Logger.Info("subscribed successfully") | ||
|
||
rd := utility.BuildSuccessResponse(http.StatusCreated, "subscribed successfully", nil) | ||
c.JSON(http.StatusCreated, rd) | ||
|
||
} |
This file contains 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 @@ | ||
package product |
This file contains 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 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,23 @@ | ||
package router | ||
|
||
import ( | ||
"fmt" | ||
|
||
"github.com/gin-gonic/gin" | ||
"github.com/go-playground/validator/v10" | ||
"github.com/hngprojects/hng_boilerplate_golang_web/external/request" | ||
"github.com/hngprojects/hng_boilerplate_golang_web/pkg/controller/newsletter" | ||
"github.com/hngprojects/hng_boilerplate_golang_web/pkg/repository/storage" | ||
"github.com/hngprojects/hng_boilerplate_golang_web/utility" | ||
) | ||
|
||
func Newsletter(r *gin.Engine, ApiVersion string, validator *validator.Validate, db *storage.Database, logger *utility.Logger) *gin.Engine { | ||
extReq := request.ExternalRequest{Logger: logger, Test: false} | ||
newsLetter := newsletter.Controller{Db: db, Validator: validator, Logger: logger, ExtReq: extReq} | ||
|
||
newsLetterUrl := r.Group(fmt.Sprintf("%v", ApiVersion)) | ||
{ | ||
newsLetterUrl.POST("/newsletter", newsLetter.SubscribeNewsLetter) | ||
} | ||
return r | ||
} |
This file contains 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 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,24 @@ | ||
package service | ||
|
||
import ( | ||
"errors" | ||
|
||
"github.com/hngprojects/hng_boilerplate_golang_web/internal/models" | ||
"github.com/hngprojects/hng_boilerplate_golang_web/pkg/repository/storage/postgresql" | ||
"gorm.io/gorm" | ||
) | ||
|
||
var ErrEmailAlreadySubscribed = errors.New("email already subscribed") | ||
|
||
func NewsLetterSubscribe(newsletter *models.NewsLetter, db *gorm.DB) error { | ||
|
||
if postgresql.CheckExists(db, newsletter, "email = ?", newsletter.Email) { | ||
return ErrEmailAlreadySubscribed | ||
} | ||
|
||
if err := newsletter.CreateNewsLetter(db); err != nil { | ||
return err | ||
} | ||
|
||
return nil | ||
} |
This file contains 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,149 @@ | ||
package tests | ||
|
||
import ( | ||
"bytes" | ||
"encoding/json" | ||
"net/http" | ||
"net/http/httptest" | ||
"testing" | ||
|
||
"github.com/gin-gonic/gin" | ||
"github.com/go-playground/validator/v10" | ||
"github.com/hngprojects/hng_boilerplate_golang_web/internal/models" | ||
"github.com/hngprojects/hng_boilerplate_golang_web/pkg/controller/newsletter" | ||
"github.com/hngprojects/hng_boilerplate_golang_web/pkg/repository/storage" | ||
) | ||
|
||
func setupNewsLetterTestRouter() (*gin.Engine, *newsletter.Controller) { | ||
gin.SetMode(gin.TestMode) | ||
|
||
logger := Setup() | ||
db := storage.Connection() | ||
validator := validator.New() | ||
|
||
newsController := &newsletter.Controller{ | ||
Db: db, | ||
Validator: validator, | ||
Logger: logger, | ||
} | ||
|
||
r := gin.Default() | ||
SetupNewsLetterRoutes(r, newsController) | ||
return r, newsController | ||
} | ||
|
||
func SetupNewsLetterRoutes(r *gin.Engine, newsController *newsletter.Controller) { | ||
r.POST("/api/v1/newsletter", newsController.SubscribeNewsLetter) | ||
} | ||
|
||
func TestE2ENewsletterSubscription(t *testing.T) { | ||
router, _ := setupNewsLetterTestRouter() | ||
|
||
// Test POST /newsletter | ||
body := models.NewsLetter{ | ||
Email: "[email protected]", | ||
} | ||
jsonBody, err := json.Marshal(body) | ||
if err != nil { | ||
t.Fatalf("Failed to marshal request body: %v", err) | ||
} | ||
|
||
req, err := http.NewRequest(http.MethodPost, "/api/v1/newsletter", bytes.NewBuffer(jsonBody)) | ||
if err != nil { | ||
t.Fatalf("Failed to create request: %v", err) | ||
} | ||
req.Header.Set("Content-Type", "application/json") | ||
resp := httptest.NewRecorder() | ||
|
||
router.ServeHTTP(resp, req) | ||
|
||
AssertStatusCode(t, resp.Code, http.StatusCreated) | ||
|
||
response := ParseResponse(resp) | ||
AssertResponseMessage(t, response["message"].(string), "subscribed successfully") | ||
} | ||
|
||
func TestPostNewsletter_ValidateEmail(t *testing.T) { | ||
router, _ := setupNewsLetterTestRouter() | ||
|
||
body := models.NewsLetter{ | ||
Email: "invalid-email", | ||
} | ||
jsonBody, _ := json.Marshal(body) | ||
|
||
req, _ := http.NewRequest(http.MethodPost, "/api/v1/newsletter", bytes.NewBuffer(jsonBody)) | ||
req.Header.Set("Content-Type", "application/json") | ||
resp := httptest.NewRecorder() | ||
|
||
router.ServeHTTP(resp, req) | ||
|
||
response := ParseResponse(resp) | ||
AssertStatusCode(t, resp.Code, http.StatusUnprocessableEntity) | ||
AssertResponseMessage(t, response["message"].(string), "Validation failed") | ||
} | ||
|
||
func TestPostNewsletter_CheckDuplicateEmail(t *testing.T) { | ||
router, newsController := setupNewsLetterTestRouter() | ||
|
||
db := newsController.Db.Postgresql | ||
db.Create(&models.NewsLetter{Email: "[email protected]"}) | ||
|
||
body := models.NewsLetter{ | ||
Email: "[email protected]", | ||
} | ||
jsonBody, _ := json.Marshal(body) | ||
|
||
req, _ := http.NewRequest(http.MethodPost, "/api/v1/newsletter", bytes.NewBuffer(jsonBody)) | ||
req.Header.Set("Content-Type", "application/json") | ||
resp := httptest.NewRecorder() | ||
|
||
router.ServeHTTP(resp, req) | ||
|
||
response := ParseResponse(resp) | ||
AssertStatusCode(t, resp.Code, http.StatusConflict) | ||
AssertResponseMessage(t, response["message"].(string), "Email already subscribed") | ||
} | ||
|
||
func TestPostNewsletter_SaveData(t *testing.T) { | ||
router, newsController := setupNewsLetterTestRouter() | ||
|
||
body := models.NewsLetter{ | ||
Email: "[email protected]", | ||
} | ||
jsonBody, _ := json.Marshal(body) | ||
|
||
req, _ := http.NewRequest(http.MethodPost, "/api/v1/newsletter", bytes.NewBuffer(jsonBody)) | ||
req.Header.Set("Content-Type", "application/json") | ||
resp := httptest.NewRecorder() | ||
|
||
router.ServeHTTP(resp, req) | ||
|
||
response := ParseResponse(resp) | ||
AssertStatusCode(t, resp.Code, http.StatusCreated) | ||
AssertResponseMessage(t, response["message"].(string), "subscribed successfully") | ||
|
||
var newsletter models.NewsLetter | ||
newsController.Db.Postgresql.First(&newsletter, "email = ?", "[email protected]") | ||
if newsletter.Email != "[email protected]" { | ||
t.Errorf("data not saved correctly to the database: expected email %s, got %s", "[email protected]", newsletter.Email) | ||
} | ||
} | ||
|
||
func TestPostNewsletter_ResponseAndStatusCode(t *testing.T) { | ||
router, _ := setupNewsLetterTestRouter() | ||
|
||
body := models.NewsLetter{ | ||
Email: "[email protected]", | ||
} | ||
jsonBody, _ := json.Marshal(body) | ||
|
||
req, _ := http.NewRequest(http.MethodPost, "/api/v1/newsletter", bytes.NewBuffer(jsonBody)) | ||
req.Header.Set("Content-Type", "application/json") | ||
resp := httptest.NewRecorder() | ||
|
||
router.ServeHTTP(resp, req) | ||
|
||
response := ParseResponse(resp) | ||
AssertStatusCode(t, resp.Code, http.StatusCreated) | ||
AssertResponseMessage(t, response["message"].(string), "subscribed successfully") | ||
} |
This file contains 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