From a0ff88cd43c266db534620bc9f299b6776d2c035 Mon Sep 17 00:00:00 2001 From: Tigor Hutasuhut Date: Fri, 26 Apr 2024 13:51:36 +0700 Subject: [PATCH] subreddits: added validation for subreddit existence on reddit when creating local subreddit --- rest/subreddits/check.http | 2 +- server/routes/subreddit_create.go | 16 +++++++++++++++- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/rest/subreddits/check.http b/rest/subreddits/check.http index 4af0ad3..acb7c1d 100644 --- a/rest/subreddits/check.http +++ b/rest/subreddits/check.http @@ -1,7 +1,7 @@ POST http://localhost:8080/api/v1/subreddits/check HTTP/1.1 Host: localhost:8080 Content-Type: application/json -Content-Length: 37 +Content-Length: 35 { "subreddit": "Wallpapers" diff --git a/server/routes/subreddit_create.go b/server/routes/subreddit_create.go index fcf3802..ec2fb8b 100644 --- a/server/routes/subreddit_create.go +++ b/server/routes/subreddit_create.go @@ -7,6 +7,8 @@ import ( "net/http" "github.com/robfig/cron/v3" + "github.com/tigorlazuardi/redmage/api" + "github.com/tigorlazuardi/redmage/api/reddit" "github.com/tigorlazuardi/redmage/models" "github.com/tigorlazuardi/redmage/pkg/errs" "github.com/tigorlazuardi/redmage/pkg/log" @@ -33,7 +35,19 @@ func (routes *Routes) SubredditsCreateAPI(rw http.ResponseWriter, req *http.Requ return } - // TODO: check if the subreddit actually exists on reddit + actual, err := routes.API.SubredditCheck(ctx, api.SubredditCheckParam{ + Subreddit: body.Name, + SubredditType: reddit.SubredditType(body.Subtype), + }) + if err != nil { + log.New(ctx).Err(err).Error("subreddit check returns error") + code, message := errs.HTTPMessage(err) + rw.WriteHeader(code) + _ = enc.Encode(map[string]string{"error": message}) + return + } + + body.Name = actual sub, err := routes.API.SubredditsCreate(ctx, body) if err != nil {