Skip to content

Commit

Permalink
add create post error
Browse files Browse the repository at this point in the history
  • Loading branch information
taryune committed Jan 6, 2023
1 parent aa52afc commit 6df92a8
Show file tree
Hide file tree
Showing 4 changed files with 57 additions and 2 deletions.
6 changes: 5 additions & 1 deletion x/blog/keeper/msg_server_create_post.go
Expand Up @@ -12,7 +12,6 @@ import (
func (k msgServer) CreatePost(goCtx context.Context, msg *types.MsgCreatePost) (*types.MsgCreatePostResponse, error) {
ctx := sdk.UnwrapSDKContext(goCtx)

// TODO: Handling the message
postCount, found := k.Keeper.GetPostCount(ctx)
if !found {
panic("postCount is not found")
Expand All @@ -25,6 +24,11 @@ func (k msgServer) CreatePost(goCtx context.Context, msg *types.MsgCreatePost) (
Body: msg.Body,
}

err := storedPost.Validate()
if err != nil {
return nil, err
}

k.Keeper.SetStoredPost(ctx, storedPost)
postCount.Count++
k.Keeper.SetPostCount(ctx, postCount)
Expand Down
20 changes: 20 additions & 0 deletions x/blog/keeper/msg_server_create_post_test.go
Expand Up @@ -29,3 +29,23 @@ func TestCreatePostSuccess(t *testing.T) {
PostIndex: "0",
}, *createResponse)
}

func TestCreatePostBadTitle(t *testing.T) {
msgServer, _, context := setupMsgServerCreatePost(t)
createResponse, err := msgServer.CreatePost(context, &types.MsgCreatePost{
Title: "",
Body: "This is a test",
})
require.Nil(t, createResponse)
require.EqualError(t, err, "index = 0: title is missing")
}

func TestCreatePostBadBody(t *testing.T) {
msgServer, _, context := setupMsgServerCreatePost(t)
createResponse, err := msgServer.CreatePost(context, &types.MsgCreatePost{
Title: "Test",
Body: "",
})
require.Nil(t, createResponse)
require.EqualError(t, err, "index = 0: body is missing")
}
4 changes: 3 additions & 1 deletion x/blog/types/errors.go
Expand Up @@ -8,5 +8,7 @@ import (

// x/blog module sentinel errors
var (
ErrSample = sdkerrors.Register(ModuleName, 1100, "sample error")
ErrSample = sdkerrors.Register(ModuleName, 1100, "sample error")
ErrMissingPostTitle = sdkerrors.Register(ModuleName, 1101, "title is missing")
ErrMissingPostBody = sdkerrors.Register(ModuleName, 1102, "body is missing")
)
29 changes: 29 additions & 0 deletions x/blog/types/full_post.go
@@ -0,0 +1,29 @@
package types

import "fmt"

func (storedPost StoredPost) GetPostTitle() (title string, err error) {
if len(storedPost.Title) <= 0 {
return title, ErrMissingPostTitle.Wrap(fmt.Sprintf("index = %s", storedPost.Index))
}
return title, nil
}

func (storedPost StoredPost) GetPostBody() (body string, err error) {
if len(storedPost.Body) <= 0 {
return body, ErrMissingPostBody.Wrap(fmt.Sprintf("index = %s", storedPost.Index))
}
return body, nil
}

func (storedPost StoredPost) Validate() (err error) {
_, err = storedPost.GetPostTitle()
if err != nil {
return err
}
_, err = storedPost.GetPostBody()
if err != nil {
return err
}
return err
}

0 comments on commit 6df92a8

Please sign in to comment.