Skip to content

Commit

Permalink
Merge pull request #47 from sapawarga/bugfix-query
Browse files Browse the repository at this point in the history
Bugfix query
  • Loading branch information
setiadijoe authored Jun 3, 2021
2 parents 380bdf8 + 224db27 commit 40fc2ff
Show file tree
Hide file tree
Showing 15 changed files with 55 additions and 56 deletions.
9 changes: 5 additions & 4 deletions endpoint/endpoint.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,15 +106,15 @@ func MakeCreateNewPost(ctx context.Context, usecase usecase.UsecaseI) endpoint.E

func MakeUpdateStatusOrTitle(ctx context.Context, usecase usecase.UsecaseI) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (response interface{}, err error) {
req := request.(*UpdateStatusOrTitle)
req := request.(*CreateCommentRequest)
if err := Validate(req); err != nil {
return nil, err
}

if err = usecase.UpdateTitleOrStatus(ctx, &model.UpdatePostRequest{
ID: req.ID,
ID: req.UserPostID,
Status: req.Status,
Title: req.Title,
Title: helper.SetPointerString(req.Text),
}); err != nil {
return nil, err
}
Expand Down Expand Up @@ -148,7 +148,8 @@ func MakeCreateComment(ctx context.Context, usecase usecase.UsecaseI) endpoint.E

if err = usecase.CreateCommentOnPost(ctx, &model.CreateCommentRequest{
UserPostID: req.UserPostID,
Text: req.Comment,
Text: req.Text,
Status: helper.GetInt64FromPointer(req.Status),
}); err != nil {
return nil, err
}
Expand Down
24 changes: 6 additions & 18 deletions endpoint/request.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,37 +32,25 @@ type Image struct {
Path string `json:"path"`
}

type UpdateStatusOrTitle struct {
ID int64 `json:"id"`
Status *int64 `json:"status"`
Title *string `json:"title"`
}

type CreateCommentRequest struct {
UserPostID int64 `json:"user_post_id"`
Comment string `json:"comment"`
Text string `json:"text"`
Status *int64 `json:"status"`
}

func Validate(in interface{}) error {
var err error
if obj, ok := in.(*CreateNewPostRequest); ok {
err = validation.ValidateStruct(in,
validation.Field(&obj.Title, validation.Required, validation.Length(0, 10)),
validation.Field(obj.Images, validation.Required, validation.By(validationImages(obj.Images))),
validation.Field(&obj.Title, validation.Required, validation.Length(10, 0)),
validation.Field(&obj.Images, validation.Required, validation.By(validationImages(obj.Images))),
validation.Field(&obj.Tags, validation.Required),
validation.Field(&obj.Status, validation.Required, validation.In(helper.ACTIVED, helper.DELETED, helper.INACTIVED)),
)
} else if obj, ok := in.(*UpdateStatusOrTitle); ok {
err = validation.ValidateStruct(in,
validation.Field(obj.ID, validation.Required),
validation.Field(&obj.Title, validation.Required, validation.Length(0, 10)),
validation.Field(&obj.Status, validation.Required, validation.In(helper.ACTIVED, helper.DELETED, helper.INACTIVED)),
)
} else if obj, ok := in.(*CreateCommentRequest); ok {
err = validation.ValidateStruct(in,
validation.Field(obj.UserPostID, validation.Required),
validation.Field(obj.Comment, validation.Required, validation.Length(0, 10)),
validation.Field(&obj.UserPostID, validation.Required),
validation.Field(&obj.Text, validation.Required, validation.Length(10, 0)),
validation.Field(&obj.Status, validation.Required, validation.In(helper.ACTIVED, helper.DELETED, helper.INACTIVED)),
)
}
Expand All @@ -75,7 +63,7 @@ func validationImages(in []*Image) validation.RuleFunc {
images := value.([]*Image)
for _, v := range images {
err = validation.ValidateStruct(v,
validation.Field(v.Path, is.URL),
validation.Field(&v.Path, is.URL),
)
}
return err
Expand Down
2 changes: 1 addition & 1 deletion mocks/testcases/create-new-post.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ var newRepositoryRequest = &model.CreateNewPostRequestRepository{
Images: "[{\"path\":\"http://localhost\"}]",
Tags: tags,
Status: helper.ACTIVED,
// ActorID: 1,
ActorID: 1,
}

type CreateNewUserPost struct {
Expand Down
7 changes: 4 additions & 3 deletions mocks/testcases/get-list-user-post.go
Original file line number Diff line number Diff line change
Expand Up @@ -119,12 +119,13 @@ var (
actorResponse = &model.UserResponse{
ID: 1,
Name: sql.NullString{String: "John Doe", Valid: true},
PhotoURL: sql.NullString{String: "sample", Valid: true},
PhotoURL: sql.NullString{String: "www.instagram.com/htm-medium=?p9878y2y3", Valid: true},
Role: sql.NullInt64{Int64: 99, Valid: true},
Regency: sql.NullString{String: "regency", Valid: true},
District: sql.NullString{String: "district", Valid: true},
Village: sql.NullString{String: "village", Valid: true},
RW: sql.NullString{String: "rw", Valid: true},
Status: 10,
}
actor = &model.Actor{
ID: 1,
Expand Down Expand Up @@ -153,8 +154,8 @@ var (
Text: commentResponse.Comment,
CreatedAt: commentResponse.CreatedAt,
UpdatedAt: commentResponse.UpdatedAt,
CreatedBy: actorResponse,
UpdatedBy: actorResponse,
CreatedBy: actor,
UpdatedBy: actor,
}
totalComment = helper.SetPointerInt64(1)
userPostResponse = []*model.UserPostResponse{
Expand Down
8 changes: 4 additions & 4 deletions mocks/testcases/get_comments.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,16 +53,16 @@ var (
Text: "comment",
CreatedAt: current,
UpdatedAt: current,
CreatedBy: actorResponse,
UpdatedBy: actorResponse,
CreatedBy: actor,
UpdatedBy: actor,
}, {
ID: 2,
UserPostID: 1,
Text: "ini juga comment",
CreatedAt: current,
UpdatedAt: current,
CreatedBy: actorResponse,
UpdatedBy: actorResponse,
CreatedBy: actor,
UpdatedBy: actor,
},
}
)
Expand Down
1 change: 1 addition & 0 deletions model/repository_request.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ type CreateCommentRequestRepository struct {
UserPostID int64
Text string
ActorID int64
Status int64
}

type CreateNewPostRequestRepository struct {
Expand Down
1 change: 1 addition & 0 deletions model/usecase_request.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ type UpdatePostRequest struct {
type CreateCommentRequest struct {
UserPostID int64 `json:"user_post_id"`
Text string `json:"comment"`
Status int64 `json:"status"`
}

type ActorFromContext struct {
Expand Down
14 changes: 7 additions & 7 deletions model/usecase_response.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,13 @@ type Metadata struct {
}

type Comment struct {
ID int64 `json:"id"`
UserPostID int64 `json:"user_post_id"`
Text string `json:"comment"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
CreatedBy *UserResponse `json:"created_by"`
UpdatedBy *UserResponse `json:"updated_by"`
ID int64 `json:"id"`
UserPostID int64 `json:"user_post_id"`
Text string `json:"comment"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
CreatedBy *Actor `json:"created_by"`
UpdatedBy *Actor `json:"updated_by"`
}

type Actor struct {
Expand Down
5 changes: 3 additions & 2 deletions repository/mysql/comment.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,13 +92,14 @@ func (r *Comment) Create(ctx context.Context, req *model.CreateCommentRequestRep
var err error
_, unixTime := helper.GetCurrentTimeUTC()

query.WriteString("INSERT INTO user_post_comments (user_post_id, `text`, status, created_by, updated_by, created_at, updated_at)")
query.WriteString("VALUES(:user_post_id. :comment, :status, :actor, :actor, :current, :current)")
query.WriteString("INSERT INTO user_post_comments (user_post_id, `text`, status, created_by, updated_by, created_at, updated_at) ")
query.WriteString("VALUES(:user_post_id, :comment, :status, :actor, :actor, :current, :current)")
params := map[string]interface{}{
"user_post_id": req.UserPostID,
"comment": req.Text,
"actor": req.ActorID,
"current": unixTime,
"status": req.Status,
}

if ctx != nil {
Expand Down
4 changes: 2 additions & 2 deletions repository/mysql/userpost.go
Original file line number Diff line number Diff line change
Expand Up @@ -263,9 +263,9 @@ func (r *UserPost) UpdateStatusOrTitle(ctx context.Context, request *model.Updat
var err error
_, unixTime := helper.GetCurrentTimeUTC()

query.WriteString("UPDATE user_posts")
query.WriteString("UPDATE user_posts SET ")
if request.Status != nil {
query.WriteString("status` = :status")
query.WriteString("status = :status")
params["status"] = request.Status
first = false
}
Expand Down
10 changes: 5 additions & 5 deletions transport/grpc/transport.go
Original file line number Diff line number Diff line change
Expand Up @@ -241,10 +241,10 @@ func encodeStatusResponse(ctx context.Context, r interface{}) (interface{}, erro
func decodeUpdateUserPost(ctx context.Context, r interface{}) (interface{}, error) {
req := r.(*transportUserPost.UpdateUserPostRequest)

return &endpoint.UpdateStatusOrTitle{
ID: req.GetId(),
Status: helper.SetPointerInt64(req.GetStatus()),
Title: helper.SetPointerString(req.GetTitle()),
return &endpoint.CreateCommentRequest{
UserPostID: req.GetId(),
Status: helper.SetPointerInt64(req.GetStatus()),
Text: req.GetTitle(),
}, nil
}

Expand Down Expand Up @@ -277,7 +277,7 @@ func decodeCreateCommentRequest(ctx context.Context, r interface{}) (interface{}

return &endpoint.CreateCommentRequest{
UserPostID: req.GetUserPostId(),
Comment: req.GetComment(),
Text: req.GetComment(),
Status: helper.SetPointerInt64(req.GetStatus()),
}, nil
}
3 changes: 1 addition & 2 deletions transport/http/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ func MakeHTTPHandler(ctx context.Context, fs usecase.UsecaseI, logger kitlog.Log
processCreatePost := kithttp.NewServer(endpoint.MakeCreateNewPost(ctx, fs), decodeCreatePost, encodeResponse, opts...)
processCreateComment := kithttp.NewServer(endpoint.MakeCreateComment(ctx, fs), decodeCreateComment, encodeResponse, opts...)
processLikeDislike := kithttp.NewServer(endpoint.MakeLikeOrDislikePost(ctx, fs), decodeGetByID, encodeResponse, opts...)
processUpdate := kithttp.NewServer(endpoint.MakeUpdateStatusOrTitle(ctx, fs), decodeGetByID, encodeResponse, opts...)
processUpdate := kithttp.NewServer(endpoint.MakeUpdateStatusOrTitle(ctx, fs), decodeCreateComment, encodeResponse, opts...)

r := mux.NewRouter()

Expand Down Expand Up @@ -100,7 +100,6 @@ func decodeCreatePost(ctx context.Context, r *http.Request) (interface{}, error)
if err := json.NewDecoder(r.Body).Decode(reqBody); err != nil {
return nil, err
}

return reqBody, nil
}

Expand Down
4 changes: 2 additions & 2 deletions usecase/parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,13 +77,13 @@ func (p *Post) getDetailComment(ctx context.Context, comment *model.CommentRespo
level.Error(logger).Log("error_get_actor_created", err)
return nil, err
}
commentResp.CreatedBy = actorCreated
commentResp.CreatedBy = p.parsingUserResponse(ctx, actorCreated)
actorUpdated, err := p.repoPost.GetActor(ctx, comment.UpdatedBy)
if err != nil {
level.Error(logger).Log("error_get_actor_updated", err)
return nil, err
}
commentResp.UpdatedBy = actorUpdated
commentResp.UpdatedBy = p.parsingUserResponse(ctx, actorUpdated)
return commentResp, nil
}

Expand Down
18 changes: 12 additions & 6 deletions usecase/usecase.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ func NewPost(repoPost repository.PostI, repoComment repository.CommentI, logger
func (p *Post) GetListPost(ctx context.Context, params *model.GetListRequest) (*model.UserPostWithMetadata, error) {
logger := kitlog.With(p.logger, "method", "GetListPost")
var limit, offset int64 = 10, 0

if params.Page != nil && params.Limit != nil {
limit = helper.GetInt64FromPointer(params.Limit)
offset = (helper.GetInt64FromPointer(params.Page) - 1) * limit
Expand Down Expand Up @@ -56,16 +55,19 @@ func (p *Post) GetListPost(ctx context.Context, params *model.GetListRequest) (*
level.Error(logger).Log("error_append_list", err)
return nil, err
}

total, err := p.repoPost.GetMetadataPost(ctx, req)
if err != nil {
level.Error(logger).Log("error_get_metadata", err)
return nil, err
}
offsetPage := helper.GetInt64FromPointer(total) % limit
if offsetPage > 0 {
offsetPage = 1
}

metadata := &model.Metadata{
Page: helper.GetInt64FromPointer(params.Page),
TotalPage: helper.GetInt64FromPointer(total) / limit,
TotalPage: helper.GetInt64FromPointer(total)/limit + offsetPage,
Total: helper.GetInt64FromPointer(total),
}

Expand Down Expand Up @@ -164,6 +166,7 @@ func (p *Post) CreateNewPost(ctx context.Context, requestBody *model.CreateNewPo
Tags: requestBody.Tags,
Status: requestBody.Status,
// ActorID: actor["id"].(int64),
ActorID: 1, // for now use default as admin
}); err != nil {
level.Error(logger).Log("error_create_post", err)
return err
Expand All @@ -173,7 +176,7 @@ func (p *Post) CreateNewPost(ctx context.Context, requestBody *model.CreateNewPo
}

func (p *Post) UpdateTitleOrStatus(ctx context.Context, requestBody *model.UpdatePostRequest) error {
logger := kitlog.With(p.logger, "method", "UpdateTItleOrStatus")
logger := kitlog.With(p.logger, "method", "UpdateTitleOrStatus")
_, err := p.repoPost.GetDetailPost(ctx, requestBody.ID)
if err != nil {
level.Error(logger).Log("error_get_detail", err)
Expand Down Expand Up @@ -223,12 +226,15 @@ func (p *Post) GetCommentsByPostID(ctx context.Context, id int64) ([]*model.Comm
}

func (p *Post) CreateCommentOnPost(ctx context.Context, req *model.CreateCommentRequest) error {
// TODO: implement authorization and authenticationn
logger := kitlog.With(p.logger, "method", "CreateCommentOnPost")
actor := ctx.Value(helper.ACTORKEY).(*model.ActorFromContext).Data
// actor := ctx.Value(helper.ACTORKEY).(*model.ActorFromContext).Data
if err := p.repoComment.Create(ctx, &model.CreateCommentRequestRepository{
UserPostID: req.UserPostID,
Text: req.Text,
ActorID: actor["id"].(int64),
Status: req.Status,
// ActorID: actor["id"].(int64),
ActorID: 1, // TODO: actor not existed yet using admin as default
}); err != nil {
level.Error(logger).Log("error_create_comment", err)
return err
Expand Down
1 change: 1 addition & 0 deletions usecase/usecase_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,7 @@ var _ = Describe("Usecase", func() {
Expect(err).NotTo(BeNil())
Expect(resp).To(BeNil())
} else {
fmt.Println(resp)
Expect(resp).To(Equal(data.ResponseUsecase.Result))
}
}
Expand Down

0 comments on commit 40fc2ff

Please sign in to comment.