Skip to content

Commit e594015

Browse files
committed
CRUD for Posts(First Part)
1 parent cc07d33 commit e594015

File tree

4 files changed

+107
-6
lines changed

4 files changed

+107
-6
lines changed

database/postgres.go

Lines changed: 35 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,13 +22,17 @@ func NewPostgreRepository(ulr string) (*PostgresRepository, error) {
2222
return &PostgresRepository{db}, nil
2323
}
2424

25-
func (repo *PostgresRepository) InsertUser (ctx context.Context, user *models.User) error {
25+
func (repo *PostgresRepository) Close() error {
26+
return repo.db.Close()
27+
}
28+
29+
func (repo *PostgresRepository) InsertUser(ctx context.Context, user *models.User) error {
2630
_, err := repo.db.ExecContext(ctx, "INSERT INTO users (id, email, password) VALUES ($1, $2, $3)",
2731
user.Id, user.Email, user.Password)
2832
return err
2933
}
3034

31-
func (repo *PostgresRepository) InsertPost (ctx context.Context, post *models.Post) error {
35+
func (repo *PostgresRepository) InsertPost(ctx context.Context, post *models.Post) error {
3236
_, err := repo.db.ExecContext(ctx, "INSERT INTO posts (id, post_content, user_id) VALUES ($1, $2, $3)",
3337
post.Id, post.PostContent, post.UserId)
3438
return err
@@ -58,8 +62,28 @@ func (repo *PostgresRepository) GetUserById(ctx context.Context, id string) (*mo
5862
return &user, nil
5963
}
6064

61-
func (repo *PostgresRepository) Close() error {
62-
return repo.db.Close()
65+
func (repo *PostgresRepository) GetPostById(ctx context.Context, id string) (*models.Post, error) {
66+
rows, err := repo.db.QueryContext(ctx, "SELECT id, post_content, created_at, user_id FROM posts WHERE id = $1", id)
67+
68+
defer func(){
69+
err = rows.Close()
70+
if err != nil {
71+
log.Fatal(err)
72+
}
73+
}()
74+
75+
var post = models.Post{}
76+
77+
for rows.Next() {
78+
if err = rows.Scan(&post.Id, &post.PostContent, &post.CreatedAt, &post.UserId); err == nil {
79+
return &post, nil
80+
}
81+
}
82+
83+
if err = rows.Err(); err != nil {
84+
return nil, err
85+
}
86+
return &post, nil
6387
}
6488

6589
func (repo *PostgresRepository) GetUserByEmail(ctx context.Context, email string) (*models.User, error) {
@@ -84,3 +108,10 @@ func (repo *PostgresRepository) GetUserByEmail(ctx context.Context, email string
84108
}
85109
return &user, nil
86110
}
111+
112+
func (repo *PostgresRepository) UpdatePost(ctx context.Context, post *models.Post) error {
113+
_, err := repo.db.ExecContext(ctx,
114+
"UPDATE posts SET post_content = $1 WHERE id = $2 and user_id = $3",
115+
post.PostContent, post.Id, post.UserId )
116+
return err
117+
}

handlers/posts.go

Lines changed: 60 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,15 @@ import (
66
"strings"
77

88
"github.com/golang-jwt/jwt/v4"
9+
"github.com/gorilla/mux"
910
"github.com/segmentio/ksuid"
1011

1112
"github.com/Euler-B/API-REST_Go/models"
1213
"github.com/Euler-B/API-REST_Go/repository"
1314
"github.com/Euler-B/API-REST_Go/server"
1415
)
1516

16-
type InsertPostRequest struct {
17+
type UpsertPostRequest struct {
1718
PostContent string `json:"post_content"`
1819
}
1920

@@ -22,6 +23,10 @@ type PostResponse struct {
2223
PostContent string `json:"post_content"`
2324
}
2425

26+
type PostUpdateResponse struct {
27+
Message string `json:"message"`
28+
}
29+
2530
func InsertPostHandler(s server.Server) http.HandlerFunc {
2631
return func(w http.ResponseWriter, r *http.Request) {
2732
tokenString := strings.TrimSpace(r.Header.Get("Authorization"))
@@ -34,7 +39,7 @@ func InsertPostHandler(s server.Server) http.HandlerFunc {
3439
return
3540
}
3641
if claims, ok := token.Claims.(*models.AppClaims); ok && token.Valid {
37-
var postRequest = InsertPostRequest{}
42+
var postRequest = UpsertPostRequest{}
3843
err := json.NewDecoder(r.Body).Decode(&postRequest);
3944
if err != nil {
4045
http.Error(w, err.Error(), http.StatusBadRequest)
@@ -65,4 +70,57 @@ func InsertPostHandler(s server.Server) http.HandlerFunc {
6570
return
6671
}
6772
}
73+
}
74+
75+
func GetPostByIdHandler(s server.Server) http.HandlerFunc {
76+
return func (w http.ResponseWriter, r *http.Request) {
77+
params := mux.Vars(r)
78+
post, err := repository.GetPostById(r.Context(), params["id"])
79+
if err != nil {
80+
http.Error(w, err.Error(), http.StatusInternalServerError)
81+
return
82+
}
83+
w.Header().Set("Content-Type", "application/json")
84+
json.NewEncoder(w).Encode(post)
85+
}
86+
}
87+
88+
func UpdatePostHandler(s server.Server) http.HandlerFunc {
89+
return func(w http.ResponseWriter, r *http.Request) {
90+
tokenString := strings.TrimSpace(r.Header.Get("Authorization")) // reto propuesto:
91+
token, err := jwt.ParseWithClaims(tokenString, &models.AppClaims{}, // buscar una forma de no repetir tanto el mismo codigo para validar tokens
92+
func(token *jwt.Token) (interface{}, error) {
93+
return []byte(s.Config().JWTSecret), nil
94+
})
95+
if err != nil {
96+
http.Error(w, err.Error(), http.StatusUnauthorized)
97+
return
98+
}
99+
if claims, ok := token.Claims.(*models.AppClaims); ok && token.Valid {
100+
params := mux.Vars(r)
101+
var postRequest = UpsertPostRequest{}
102+
err := json.NewDecoder(r.Body).Decode(&postRequest);
103+
if err != nil {
104+
http.Error(w, err.Error(), http.StatusBadRequest)
105+
return
106+
}
107+
post := models.Post{
108+
Id: params["id"],
109+
PostContent: postRequest.PostContent,
110+
UserId: claims.UserId,
111+
}
112+
err = repository.UpdatePost(r.Context(), &post)
113+
if err != nil {
114+
http.Error(w, err.Error(), http.StatusInternalServerError)
115+
return
116+
}
117+
w.Header().Set("Content-Type", "application/json")
118+
json.NewEncoder(w).Encode(PostUpdateResponse{
119+
Message: "Post Updated",
120+
})
121+
} else {
122+
http.Error(w, err.Error(), http.StatusInternalServerError)
123+
return
124+
}
125+
}
68126
}

main.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,4 +47,6 @@ func BindRoutes(s server.Server, r *mux.Router) {
4747
r.HandleFunc("/me", handlers.MeHandler(s)).Methods(http.MethodGet)
4848

4949
r.HandleFunc("/posts", handlers.InsertPostHandler(s)).Methods(http.MethodPost)
50+
r.HandleFunc("/posts/{id}", handlers.GetPostByIdHandler(s)).Methods(http.MethodGet)
51+
r.HandleFunc("/posts/{id}", handlers.UpdatePostHandler(s)).Methods(http.MethodPut)
5052
}

repository/repository.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@ type Repository interface {
1212
GetUserById(ctx context.Context, id string) (*models.User, error)
1313
GetUserByEmail(ctx context.Context, email string) (*models.User, error)
1414
InsertPost(ctx context.Context, post *models.Post) error
15+
GetPostById(ctx context.Context, id string) (*models.Post, error)
16+
UpdatePost(ctx context.Context, post *models.Post) error
1517
Close() error
1618
}
1719

@@ -39,4 +41,12 @@ func GetUserByEmail(ctx context.Context, email string) (*models.User, error) {
3941

4042
func InsertPost(ctx context.Context, post *models.Post) error {
4143
return implementation.InsertPost(ctx, post)
44+
}
45+
46+
func GetPostById(ctx context.Context, id string) (*models.Post, error) {
47+
return implementation.GetPostById(ctx, id)
48+
}
49+
50+
func UpdatePost(ctx context.Context, post *models.Post) error {
51+
return implementation.UpdatePost(ctx, post)
4252
}

0 commit comments

Comments
 (0)