Skip to content

Commit

Permalink
Merge pull request #58 from sapawarga/bugfix-response-json
Browse files Browse the repository at this point in the history
Bugfix response json
  • Loading branch information
setiadijoe authored Jun 23, 2021
2 parents 230ba3c + c8e6438 commit b767de7
Show file tree
Hide file tree
Showing 11 changed files with 102 additions and 59 deletions.
1 change: 1 addition & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ APP_ENV=local
APP_GRPC_PORT=3000
APP_HTTP_PORT=3001
APP_DEBUG=true
APP_STORAGE_PUBLIC_URL=

DB_HOST=localhost
DB_PORT=3306
Expand Down
2 changes: 2 additions & 0 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ func NewConfig() (defConfig *Config, err error) {
appGRPCPort, _ := strconv.Atoi(os.Getenv(`APP_GRPC_PORT`))
appHTTPPort, _ := strconv.Atoi(os.Getenv(`APP_HTTP_PORT`))
debugString := os.Getenv(`APP_DEBUG`)
appStoragePublicURL := os.Getenv(`APP_STORAGE_PUBLIC_URL`)
debug := false

if debugString == "true" {
Expand All @@ -39,6 +40,7 @@ func NewConfig() (defConfig *Config, err error) {
defConfig.AppGRPCPort = appGRPCPort
defConfig.AppHTTPPort = appHTTPPort
defConfig.Debug = debug
defConfig.AppStoragePublicURL = appStoragePublicURL

if dbHost == "" || dbPort == 0 || dbUser == "" || dbName == "" || driverName == "" {
err = fmt.Errorf("[CONFIG][Critical] Please check section DB on %s", envFileName)
Expand Down
11 changes: 6 additions & 5 deletions config/model.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,10 @@ type DB struct {
}

type Config struct {
AppGRPCPort int `env:"APP_GRPC_PORT,required"`
AppHTTPPort int `env:"APP_HTTP_PORT,required"`
AppEnv string `env:"APP_ENV,required"`
Debug bool `env:"APP_DEBUG,required"`
DB *DB
AppGRPCPort int `env:"APP_GRPC_PORT,required"`
AppHTTPPort int `env:"APP_HTTP_PORT,required"`
AppEnv string `env:"APP_ENV,required"`
Debug bool `env:"APP_DEBUG,required"`
AppStoragePublicURL string `env:"APP_STORAGE_PUBLIC_URL,required"`
DB *DB
}
8 changes: 3 additions & 5 deletions endpoint/endpoint.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package endpoint
import (
"context"
"encoding/json"
"strings"

"errors"

Expand All @@ -16,10 +15,9 @@ import (
func MakeGetListUserPost(ctx context.Context, usecase usecase.UsecaseI) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (response interface{}, err error) {
req := request.(*GetListUserPostRequest)
cASC := strings.Compare(helper.GetStringFromPointer(req.SortBy), "ASC")
cDESC := strings.Compare(helper.GetStringFromPointer(req.SortBy), "DESC")
if req.SortBy != nil && (cASC*cDESC == 1) {
return nil, errors.New("must_between_ASC_DESC")
orderBy := helper.GetStringFromPointer(req.OrderBy)
if req.OrderBy != nil && !isOrderValid(orderBy) {
return nil, errors.New("order_must_between_ASC_DESC")
}
// TODO: for get metadata from headers grpc needs to update when using authorization
resp, err := usecase.GetListPost(ctx, &model.GetListRequest{
Expand Down
6 changes: 6 additions & 0 deletions endpoint/request.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package endpoint

import (
"strings"

"github.com/go-ozzo/ozzo-validation/is"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/sapawarga/userpost-service/helper"
Expand Down Expand Up @@ -69,3 +71,7 @@ func validationImages(in []*Image) validation.RuleFunc {
return err
}
}

func isOrderValid(val string) bool {
return strings.EqualFold(val, "ASC") || strings.EqualFold(val, "DESC")
}
5 changes: 4 additions & 1 deletion mocks/testcases/get-detail-user-post.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,15 @@ type ResponseGetDetailUsecase struct {
}

var (
images = []map[string]interface{}{
{"path": "general"},
}
userpostResponse = &model.UserPostResponse{
ID: 1,
Title: "title",
Tag: helper.SetPointerString("tag"),
ImagePath: "test",
Images: "test",
Images: images,
LastUserPostCommentID: helper.SetPointerInt64(1),
LastComment: comment,
LikesCount: 0,
Expand Down
23 changes: 12 additions & 11 deletions mocks/testcases/get-list-user-post.go
Original file line number Diff line number Diff line change
Expand Up @@ -128,15 +128,16 @@ var (
Status: 10,
}
actor = &model.Actor{
ID: 1,
Name: "John Doe",
PhotoURL: "www.instagram.com/htm-medium=?p9878y2y3",
Role: 99,
Regency: "regency",
District: "district",
Village: "village",
RW: "rw",
Status: 10,
ID: 1,
Name: "John Doe",
PhotoURL: "www.instagram.com/htm-medium=?p9878y2y3",
Role: 99,
RoleLabel: model.RoleLabel[int64(99)],
Regency: "regency",
District: "district",
Village: "village",
RW: "rw",
Status: 10,
}
metadataResponse = helper.SetPointerInt64(2)
commentResponse = &model.CommentResponse{
Expand Down Expand Up @@ -164,7 +165,7 @@ var (
Title: "title",
Tag: helper.SetPointerString("tag"),
ImagePath: "test",
Images: "test",
Images: images,
LastUserPostCommentID: helper.SetPointerInt64(1),
LastComment: comment,
LikesCount: 0,
Expand All @@ -179,7 +180,7 @@ var (
Title: "test title",
Tag: helper.SetPointerString("tag"),
ImagePath: "test",
Images: "test",
Images: images,
LastUserPostCommentID: helper.SetPointerInt64(1),
LastComment: comment,
LikesCount: 0,
Expand Down
62 changes: 39 additions & 23 deletions model/usecase_response.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,20 @@ import (
)

type UserPostResponse struct {
ID int64 `json:"id"`
Title string `json:"title"`
Tag *string `json:"tags,omitempty"`
ImagePath string `json:"image_path,omitempty"`
Images string `json:"images"`
LastUserPostCommentID *int64 `json:"last_user_post_comment_id,omitempty"`
LastComment *Comment `json:"last_comment,omitempty"`
LikesCount int64 `json:"likes_count"`
IsLiked bool `json:"is_liked"`
CommentCounts int64 `json:"comment_counts"`
Status int64 `json:"status"`
Actor *Actor `json:"actor"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
ID int64 `json:"id"`
Title string `json:"title"`
Tag *string `json:"tags,omitempty"`
ImagePath string `json:"image_path,omitempty"`
Images []map[string]interface{} `json:"images"`
LastUserPostCommentID *int64 `json:"last_user_post_comment_id,omitempty"`
LastComment *Comment `json:"last_comment,omitempty"`
LikesCount int64 `json:"likes_count"`
IsLiked bool `json:"is_liked"`
CommentCounts int64 `json:"comment_counts"`
Status int64 `json:"status"`
Actor *Actor `json:"actor"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}

type UserPostWithMetadata struct {
Expand All @@ -43,13 +43,29 @@ type Comment struct {
}

type Actor struct {
ID int64 `json:"id"`
Name string `json:"name"`
PhotoURL string `json:"photo_url,omitempty"`
Role int64 `json:"role,omitempty"`
Regency string `json:"regency,omitempty"`
District string `json:"district,omitempty"`
Village string `json:"village,omitempty"`
RW string `json:"rw,omitempty"`
Status int64 `json:"status,omitempty"`
ID int64 `json:"id"`
Name string `json:"name"`
PhotoURL string `json:"photo_url,omitempty"`
Role int64 `json:"role,omitempty"`
RoleLabel string `json:"role_label,omitempty"`
Regency string `json:"regency,omitempty"`
District string `json:"district,omitempty"`
Village string `json:"village,omitempty"`
RW string `json:"rw,omitempty"`
Status int64 `json:"status,omitempty"`
}

var RoleLabel = map[int64]string{
10: "user",
49: "trainer",
50: "staffRW",
60: "staffKel",
70: "staffKec",
80: "staffKabKota",
88: "staffOPD",
89: "staffSaberhoax",
90: "staffProv",
91: "pimpinan",
99: "admin",
100: "service_account",
}
2 changes: 1 addition & 1 deletion repository/mysql/userpost.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ func (r *UserPost) GetListPost(ctx context.Context, request *model.UserPostReque
params = append(params, request.Offset, request.Limit)
}
if request.OrderBy != nil && request.SortBy != nil {
query.WriteString(fmt.Sprintf(" ORDER BY %s %s", *request.OrderBy, *request.SortBy))
query.WriteString(fmt.Sprintf(" ORDER BY %s %s", *request.SortBy, *request.OrderBy))
}
if ctx != nil {
err = r.conn.SelectContext(ctx, &result, query.String(), params...)
Expand Down
7 changes: 5 additions & 2 deletions transport/grpc/transport.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package grpc

import (
"context"
"encoding/json"

"github.com/sapawarga/userpost-service/endpoint"
"github.com/sapawarga/userpost-service/helper"
Expand Down Expand Up @@ -96,12 +97,13 @@ func encodeGetListUserPost(ctx context.Context, r interface{}) (interface{}, err
resultData := make([]*transportUserPost.UserPost, 0)

for _, v := range data {
images, _ := json.Marshal(v.Images)
result := &transportUserPost.UserPost{
Id: v.ID,
Title: v.Title,
Tag: helper.GetStringFromPointer(v.Tag),
ImagePath: v.ImagePath,
Images: v.Images,
Images: string(images),
LastUserPostCommentId: helper.GetInt64FromPointer(v.LastUserPostCommentID),
LikesCount: v.LikesCount,
CommentCounts: v.CommentCounts,
Expand Down Expand Up @@ -175,12 +177,13 @@ func encodedUserPostDetail(ctx context.Context, r interface{}) (interface{}, err

actorUserPost := encodeActor(ctx, resp.Actor)

images, _ := json.Marshal(resp.Images)
userDetail := &transportUserPost.UserPost{
Id: resp.ID,
Title: resp.Title,
Tag: helper.GetStringFromPointer(resp.Tag),
ImagePath: resp.ImagePath,
Images: resp.Images,
Images: string(images),
LastUserPostCommentId: helper.GetInt64FromPointer(resp.LastUserPostCommentID),
LastComment: lastComment,
LikesCount: resp.LikesCount,
Expand Down
34 changes: 23 additions & 11 deletions usecase/parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,32 @@ package usecase

import (
"context"
"encoding/json"
"fmt"

kitlog "github.com/go-kit/kit/log"
"github.com/go-kit/kit/log/level"
"github.com/sapawarga/userpost-service/config"
"github.com/sapawarga/userpost-service/helper"
"github.com/sapawarga/userpost-service/model"
)

func (p *Post) getDetailOfUserPost(ctx context.Context, post *model.PostResponse) (*model.UserPostResponse, error) {
logger := kitlog.With(p.logger, "method", "getDetailOfUserPost")
cfg, _ := config.NewConfig()
images := make([]map[string]interface{}, 0)
if err := json.Unmarshal([]byte(post.Images.String), &images); err != nil {
images = nil
}
for _, v := range images {
v["path"] = fmt.Sprintf("%s/%s", cfg.AppStoragePublicURL, v["path"])
}
userPost := &model.UserPostResponse{
ID: post.ID,
Title: post.Title,
Tag: helper.SetPointerString(post.Tag.String),
ImagePath: post.ImagePath.String,
Images: post.Images.String,
ImagePath: fmt.Sprintf("%s/%s", cfg.AppStoragePublicURL, post.ImagePath.String),
Images: images,
LikesCount: post.LikesCount,
CommentCounts: post.CommentCounts,
Status: post.Status,
Expand Down Expand Up @@ -51,15 +62,16 @@ func (p *Post) getDetailOfUserPost(ctx context.Context, post *model.PostResponse

func (p *Post) parsingUserResponse(ctx context.Context, user *model.UserResponse) *model.Actor {
return &model.Actor{
ID: user.ID,
Name: user.Name.String,
PhotoURL: user.PhotoURL.String,
Role: user.Role.Int64,
Regency: user.Regency.String,
District: user.District.String,
Village: user.Village.String,
RW: user.RW.String,
Status: user.Status,
ID: user.ID,
Name: user.Name.String,
PhotoURL: user.PhotoURL.String,
Role: user.Role.Int64,
RoleLabel: model.RoleLabel[user.Role.Int64],
Regency: user.Regency.String,
District: user.District.String,
Village: user.Village.String,
RW: user.RW.String,
Status: user.Status,
}
}

Expand Down

0 comments on commit b767de7

Please sign in to comment.