This repository has been archived by the owner on Nov 15, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 19
Issue 41 #118
Open
andersondalmina
wants to merge
3
commits into
master
Choose a base branch
from
issue-41
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Issue 41 #118
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
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
13 changes: 13 additions & 0 deletions
13
devops/migrations/20180523161835-create_subscribers_table.sql
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,13 @@ | ||
|
||
-- +migrate Up | ||
CREATE TABLE subscriptions ( | ||
id SERIAL PRIMARY KEY, | ||
organization_id INTEGER NOT NULL REFERENCES organizations (id) ON UPDATE CASCADE ON DELETE RESTRICT, | ||
name VARCHAR(100) NOT NULL, | ||
email VARCHAR(255) NOT NULL, | ||
phone VARCHAR(45) NOT NULL, | ||
date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP | ||
); | ||
|
||
-- +migrate Down | ||
DROP TABLE subscriptions; |
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,93 @@ | ||
package repo | ||
|
||
import ( | ||
"database/sql" | ||
"errors" | ||
"fmt" | ||
"strings" | ||
|
||
"github.com/Coderockr/vitrine-social/server/model" | ||
"github.com/jmoiron/sqlx" | ||
) | ||
|
||
// SubscriptionRepository is a implementation for Postgres | ||
type SubscriptionRepository struct { | ||
db *sqlx.DB | ||
orgRepo *OrganizationRepository | ||
} | ||
|
||
// NewSubscriptionRepository creates a new repository | ||
func NewSubscriptionRepository(db *sqlx.DB) *SubscriptionRepository { | ||
return &SubscriptionRepository{ | ||
db: db, | ||
orgRepo: NewOrganizationRepository(db), | ||
} | ||
} | ||
|
||
// Create new subscription | ||
func (r *SubscriptionRepository) Create(s model.Subscription) (model.Subscription, error) { | ||
s, err := validate(r, s) | ||
|
||
if err != nil { | ||
return s, err | ||
} | ||
|
||
row := r.db.QueryRow( | ||
`INSERT INTO subscriptions (organization_id, name, email, phone) | ||
VALUES($1, $2, $3, $4) | ||
RETURNING id | ||
`, | ||
s.OrganizationID, | ||
s.Name, | ||
s.Email, | ||
s.Phone, | ||
) | ||
|
||
err = row.Scan(&s.ID) | ||
|
||
if err != nil { | ||
return s, err | ||
} | ||
|
||
return s, nil | ||
} | ||
|
||
func validate(r *SubscriptionRepository, s model.Subscription) (model.Subscription, error) { | ||
s.Name = strings.TrimSpace(s.Name) | ||
if len(s.Name) == 0 { | ||
return s, errors.New("Deve ser informado um nome para a Inscrição") | ||
} | ||
|
||
s.Email = strings.TrimSpace(s.Email) | ||
if len(s.Email) == 0 { | ||
return s, errors.New("Deve ser informado um email para a Inscrição") | ||
} | ||
|
||
s.Phone = strings.TrimSpace(s.Phone) | ||
if len(s.Phone) == 0 { | ||
return s, errors.New("Deve ser informado um telefone para a Inscrição") | ||
} | ||
|
||
_, err := getBaseOrganization(r.db, s.OrganizationID) | ||
switch { | ||
case err == sql.ErrNoRows: | ||
return s, fmt.Errorf("Não foi encontrada Organização com ID: %d", s.OrganizationID) | ||
case err != nil: | ||
return s, err | ||
} | ||
|
||
var found int64 | ||
err = r.db.QueryRow(` | ||
SELECT COUNT(1) as found | ||
FROM subscriptions | ||
WHERE organization_id = $1 AND email LIKE $2`, | ||
s.OrganizationID, | ||
s.Email, | ||
).Scan(&found) | ||
|
||
if found > 0 { | ||
return s, fmt.Errorf("Este email já está inscrito para a Organização %d", s.OrganizationID) | ||
} | ||
|
||
return s, 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,53 @@ | ||
package handlers | ||
|
||
import ( | ||
"fmt" | ||
"net/http" | ||
"strconv" | ||
"time" | ||
|
||
"github.com/Coderockr/vitrine-social/server/model" | ||
"github.com/gorilla/mux" | ||
) | ||
|
||
type ( | ||
// SubscriptionRepository represet operations for subscription repository. | ||
SubscriptionRepository interface { | ||
Create(model.Subscription) (model.Subscription, error) | ||
} | ||
) | ||
|
||
// CreateSubscriptionHandler create a new subscription | ||
func CreateSubscriptionHandler(repo SubscriptionRepository) func(w http.ResponseWriter, r *http.Request) { | ||
return func(w http.ResponseWriter, r *http.Request) { | ||
urlVars := mux.Vars(r) | ||
id, err := strconv.ParseInt(urlVars["id"], 10, 64) | ||
if err != nil { | ||
HandleHTTPError(w, http.StatusBadRequest, fmt.Errorf("Não foi possível entender o número: %s", urlVars["id"])) | ||
return | ||
} | ||
|
||
var bodyVars map[string]string | ||
err = requestToJSONObject(r, &bodyVars) | ||
if err != nil { | ||
HandleHTTPError(w, http.StatusBadRequest, err) | ||
return | ||
} | ||
|
||
now := time.Now() | ||
s, err := repo.Create(model.Subscription{ | ||
OrganizationID: id, | ||
Email: bodyVars["email"], | ||
Name: bodyVars["name"], | ||
Phone: bodyVars["phone"], | ||
Date: &now, | ||
}) | ||
|
||
if err != nil { | ||
HandleHTTPError(w, http.StatusBadRequest, err) | ||
return | ||
} | ||
|
||
HandleHTTPSuccess(w, map[string]int64{"id": s.ID}) | ||
} | ||
} |
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,113 @@ | ||
package handlers_test | ||
|
||
import ( | ||
"errors" | ||
"fmt" | ||
"io/ioutil" | ||
"net/http" | ||
"net/http/httptest" | ||
"strings" | ||
"testing" | ||
|
||
"github.com/Coderockr/vitrine-social/server/handlers" | ||
"github.com/Coderockr/vitrine-social/server/model" | ||
"github.com/gorilla/mux" | ||
"github.com/stretchr/testify/require" | ||
) | ||
|
||
type ( | ||
subscriptionRepositoryMock struct { | ||
CreateFN func(model.Subscription) (model.Subscription, error) | ||
} | ||
) | ||
|
||
func TestCreateSubscriptionHandler(t *testing.T) { | ||
type params struct { | ||
organizationID string | ||
repository handlers.SubscriptionRepository | ||
} | ||
|
||
tests := map[string]struct { | ||
body string | ||
status int | ||
response string | ||
params params | ||
}{ | ||
"should fail beacuse trying to create without parameters": { | ||
body: ``, | ||
status: http.StatusBadRequest, | ||
response: ``, | ||
params: params{ | ||
organizationID: "1", | ||
repository: &subscriptionRepositoryMock{ | ||
CreateFN: func(model.Subscription) (model.Subscription, error) { | ||
s := model.Subscription{} | ||
return s, errors.New("Deve ser informado um nome para a Inscrição") | ||
}, | ||
}, | ||
}, | ||
}, | ||
"should fail beacuse trying to create with no valid organization": { | ||
body: ``, | ||
status: http.StatusBadRequest, | ||
response: ``, | ||
params: params{ | ||
organizationID: "5", | ||
repository: &subscriptionRepositoryMock{ | ||
CreateFN: func(model.Subscription) (model.Subscription, error) { | ||
s := model.Subscription{} | ||
return s, fmt.Errorf("Não foi encontrada Organização com ID: 5") | ||
}, | ||
}, | ||
}, | ||
}, | ||
"should success beacuse the right values were sent": { | ||
body: `{ | ||
"name": "Coderockr Test", | ||
"email": "test@coderockr.com", | ||
"phone": "(54) 99999-9999" | ||
}`, | ||
status: http.StatusOK, | ||
response: `{ | ||
"id": 1 | ||
}`, | ||
params: params{ | ||
organizationID: "1", | ||
repository: &subscriptionRepositoryMock{ | ||
CreateFN: func(model.Subscription) (model.Subscription, error) { | ||
s := model.Subscription{ | ||
ID: 1, | ||
Name: "Coderockr Test", | ||
Email: "test@coderockr.com", | ||
Phone: "(54) 99999-9999", | ||
} | ||
return s, nil | ||
}, | ||
}, | ||
}, | ||
}, | ||
} | ||
|
||
for name, v := range tests { | ||
t.Run(name, func(t *testing.T) { | ||
r, _ := http.NewRequest("POST", "/v1/organization/"+v.params.organizationID+"/subscribe", strings.NewReader(v.body)) | ||
r = mux.SetURLVars(r, map[string]string{"id": v.params.organizationID}) | ||
|
||
resp := httptest.NewRecorder() | ||
|
||
handlers.CreateSubscriptionHandler(v.params.repository)(resp, r) | ||
|
||
result := resp.Result() | ||
body, _ := ioutil.ReadAll(result.Body) | ||
|
||
if len(v.response) > 0 { | ||
require.JSONEq(t, v.response, string(body)) | ||
} | ||
require.Equal(t, v.status, resp.Code) | ||
}) | ||
} | ||
} | ||
|
||
func (r *subscriptionRepositoryMock) Create(s model.Subscription) (model.Subscription, error) { | ||
return r.CreateFN(s) | ||
} |
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
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@leandro-lugaresi @eminetto quando usamos serviços como o
MailChimp
e semelhantes, a gente precisa manter os dados das pessoas? ou o serviço lida sozinho com isso?