Skip to content

Commit 8dd596c

Browse files
committed
Fix bug where empty posts were allowed
There was a bug where you can submit an empty post, but this has been fixed by setting a constraint to check for an empty content field in the posts table. Changes made to drumstick.sql file - added non_empty_column constraint to the posts table to check for empty posts in the content column. Changes made to posts.go file - Reformatted the way errs are returned for failed posts in the CreatePosts func for clarity.
1 parent 60aa7de commit 8dd596c

2 files changed

Lines changed: 9 additions & 3 deletions

File tree

drumstick.sql

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,8 @@ CREATE TABLE public.posts (
4242
user_id integer NOT NULL,
4343
parent_id integer NOT NULL,
4444
thread_id integer DEFAULT nextval('public.posts_thread_id_seq'::regclass) NOT NULL,
45-
content character varying(350) NOT NULL
45+
content character varying(350) NOT NULL,
46+
CONSTRAINT non_empty_column CHECK ((length(TRIM(BOTH FROM content)) > 0))
4647
);
4748

4849

internal/posts/posts.go

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import (
88

99
"github.com/georgysavva/scany/v2/pgxscan"
1010
"github.com/jackc/pgx/v5"
11+
"github.com/jackc/pgx/v5/pgconn"
1112
)
1213

1314
type Post struct {
@@ -51,9 +52,13 @@ func CreatePosts(userPost, email string) (*Post, error) {
5152
&tempPost.ThreadID, &tempPost.Content,
5253
)
5354

54-
// check list all the errs
5555
if err != nil {
56-
return nil, fmt.Errorf("error: %w", err)
56+
var pgErr *pgconn.PgError
57+
if errors.As(err, &pgErr) {
58+
return nil, fmt.Errorf("error: %s", pgErr.Message)
59+
}
5760
}
61+
62+
// check list all the errs
5863
return tempPost, nil
5964
}

0 commit comments

Comments
 (0)