Skip to content

Commit

Permalink
Merge pull request #43 from sapawarga/enhancement/docker-setting-env
Browse files Browse the repository at this point in the history
Enhancement/docker setting env
  • Loading branch information
setiadijoe authored May 25, 2021
2 parents 438eebd + d1f2bfb commit 1fcd148
Show file tree
Hide file tree
Showing 9 changed files with 60 additions and 88 deletions.
19 changes: 4 additions & 15 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -11,28 +11,17 @@ WORKDIR /build

COPY go.mod .
COPY go.sum .
COPY .env.example ./.env
RUN go mod download
RUN go mod download -x

COPY . .

RUN CGO_ENABLED=0 go test -v ./...
RUN make build

FROM alpine:3.11.3 as run-image
FROM gcr.io/distroless/base-debian10

LABEL maintainer="GoSapawarga <[email protected]>"

ENV PROJECT_PATH=/build
COPY --from=compile-image /build /

WORKDIR /app

RUN apk --update add tzdata ca-certificates && \
update-ca-certificates 2>/dev/null || true

COPY --from=compile-image ${PROJECT_PATH}/userpost-service /app/userpost-service
COPY --from=compile-image ${PROJECT_PATH}/.env /app/.env

EXPOSE 3002 3003

ENTRYPOINT [ "/app/userpost-service" ]
ENTRYPOINT [ "/userpost-service" ]
35 changes: 22 additions & 13 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package config

import (
"fmt"
"os"
"strconv"

_ "github.com/go-sql-driver/mysql"
"github.com/spf13/viper"
Expand All @@ -22,26 +24,33 @@ func init() {
//NewConfig ...
func NewConfig() (defConfig *Config, err error) {
defConfig = &Config{}
appEnv := viper.GetString(`APP_ENV`)
appGrpcPort := viper.GetInt(`APP_GRPC_PORT`)
appHttpPort := viper.GetInt(`APP_HTTP_PORT`)
debug := viper.GetBool(`APP_DEBUG`)
appEnv := os.Getenv(`APP_ENV`)
// appGRPCPort, _ := strconv.Atoi(os.Getenv(`APP_GRPC_PORT`))
appGRPCPort := 9005
// appHTTPPort, _ := strconv.Atoi(os.Getenv(`APP_HTTP_PORT`))
appHTTPPort := 9006
debugString := os.Getenv(`APP_DEBUG`)
debug := false

dbHost := viper.GetString(`DB_HOST`)
dbPort := viper.GetInt(`DB_PORT`)
dbUser := viper.GetString(`DB_USER`)
dbPassword := viper.GetString(`DB_PASS`)
dbName := viper.GetString(`DB_NAME`)
driverName := viper.GetString(`DB_DRIVER_NAME`)
if debugString == "true" {
debug = true
}

dbHost := os.Getenv(`DB_HOST`)
dbPort, _ := strconv.Atoi(os.Getenv(`DB_PORT`))
dbUser := os.Getenv(`DB_USER`)
dbPassword := os.Getenv(`DB_PASS`)
dbName := os.Getenv(`DB_NAME`)
driverName := os.Getenv(`DB_DRIVER_NAME`)

if appEnv == "" || appGrpcPort == 0 || appHttpPort == 0 {
if appEnv == "" || appGRPCPort == 0 || appHTTPPort == 0 {
err = fmt.Errorf("[CONFIG][Critical] Please check section APP on %s", envFileName)
return defConfig, err
}

defConfig.AppEnv = appEnv
defConfig.AppGRPCPort = appGrpcPort
defConfig.AppHTTPPort = appHttpPort
defConfig.AppGRPCPort = appGRPCPort
defConfig.AppHTTPPort = appHTTPPort
defConfig.Debug = debug

if dbHost == "" || dbPort == 0 || dbUser == "" || dbName == "" || driverName == "" {
Expand Down
4 changes: 2 additions & 2 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ services:
env_file:
- .env
ports:
- 3002:3002
- 3003:3003
- 9005:9005
- 9006:9006

# database:
# image: registry.gitlab.com/jdsteam/sapa-warga/sapawarga-app/sapawarga-backend-database:dev
Expand Down
27 changes: 0 additions & 27 deletions endpoint/endpoint.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,26 +3,17 @@ package endpoint
import (
"context"
"encoding/json"
"errors"

"github.com/go-kit/kit/endpoint"
"github.com/sapawarga/userpost-service/helper"
"github.com/sapawarga/userpost-service/model"
"github.com/sapawarga/userpost-service/usecase"
"google.golang.org/grpc/metadata"
)

func MakeGetListUserPost(ctx context.Context, usecase usecase.UsecaseI) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (response interface{}, err error) {
req := request.(*GetListUserPostRequest)
// TODO: for get metadata from headers grpc needs to update when using authorization
headers, ok := metadata.FromIncomingContext(ctx)
if !ok {
return nil, errors.New("invalid_metadata")
}
actor := headers["Actor"]
ctx = context.WithValue(ctx, helper.ACTORKEY, actor)

resp, err := usecase.GetListPost(ctx, &model.GetListRequest{
ActivityName: req.ActivityName,
Username: req.Username,
Expand Down Expand Up @@ -52,12 +43,6 @@ func MakeGetDetailUserPost(ctx context.Context, usecase usecase.UsecaseI) endpoi
return func(ctx context.Context, request interface{}) (response interface{}, err error) {
req := request.(*GetByID)
// TODO: for get metadata from headers grpc needs to update when using authorization
headers, ok := metadata.FromIncomingContext(ctx)
if !ok {
return nil, errors.New("invalid_metadata")
}
actor := headers["Actor"]
ctx = context.WithValue(ctx, helper.ACTORKEY, actor)
resp, err := usecase.GetDetailPost(ctx, req.ID)
if err != nil {
return nil, err
Expand All @@ -70,12 +55,6 @@ func MakeGetListUserPostByMe(ctx context.Context, usecase usecase.UsecaseI) endp
return func(ctx context.Context, request interface{}) (response interface{}, err error) {
req := request.(*GetListUserPostRequest)
// TODO: for get metadata from headers grpc needs to update when using authorization
headers, ok := metadata.FromIncomingContext(ctx)
if !ok {
return nil, errors.New("invalid_metadata")
}
actor := headers["Actor"]
ctx = context.WithValue(ctx, helper.ACTORKEY, actor)
response, err = usecase.GetListPostByMe(ctx, &model.GetListRequest{
ActivityName: req.ActivityName,
Username: req.Username,
Expand Down Expand Up @@ -185,12 +164,6 @@ func MakeLikeOrDislikePost(ctx context.Context, usecase usecase.UsecaseI) endpoi
return func(ctx context.Context, request interface{}) (response interface{}, err error) {
req := request.(*GetByID)
// TODO: for get metadata from headers grpc needs to update when using authorization
headers, ok := metadata.FromIncomingContext(ctx)
if !ok {
return nil, errors.New("invalid_metadata")
}
actor := headers["Actor"]
ctx = context.WithValue(ctx, helper.ACTORKEY, actor)
if err = usecase.LikeOrDislikePost(ctx, req.ID); err != nil {
return nil, 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
2 changes: 1 addition & 1 deletion mocks/testcases/likeordislike.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import (

var requestLikeOnPost = &model.AddOrRemoveLikeOnPostRequest{
UserPostID: 1,
ActorID: 1,
// ActorID: 1,
TypeEntity: "user_post",
}

Expand Down
2 changes: 1 addition & 1 deletion model/repository_response.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ type PostResponse struct {
Images sql.NullString `db:"images"`
LastUserPostCommentID sql.NullInt64 `db:"last_user_post_comment_id"`
LikesCount int64 `db:"likes_count"`
CommentCounts int64 `db:"comment_counts"`
CommentCounts int64 `db:"comments_count"`
Status int64 `db:"status"`
CreatedBy sql.NullInt64 `db:"created_by"`
UpdatedBy sql.NullInt64 `db:"updated_by"`
Expand Down
33 changes: 15 additions & 18 deletions repository/mysql/userpost.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ func (r *UserPost) GetListPost(ctx context.Context, request *model.UserPostReque
var result = make([]*model.PostResponse, 0)
var err error

query.WriteString("SELECT id, text, tags. image_path, images, last_user_post_comment_id, likes_count, comment_counts, status, created_by, updated_by, create_at, updated_at FROM userposts")
query.WriteString("SELECT id, text, tags, image_path, images, last_user_post_comment_id, likes_count, comments_count, status, created_by, updated_by, FROM_UNIXTIME(created_at) as created_at, FROM_UNIXTIME(updated_at) as updated_at FROM user_posts")
query, params := querySelectParams(ctx, query, request)
if request.Limit != nil && request.Offset != nil {
query.WriteString("LIMIT ?, ?")
Expand All @@ -37,9 +37,9 @@ func (r *UserPost) GetListPost(ctx context.Context, request *model.UserPostReque
params = append(params, request.OrderBy, request.SortBy)
}
if ctx != nil {
err = r.conn.SelectContext(ctx, result, query.String(), params...)
err = r.conn.SelectContext(ctx, &result, query.String(), params...)
} else {
err = r.conn.Select(result, query.String(), params...)
err = r.conn.Select(&result, query.String(), params...)
}

if err != nil {
Expand All @@ -54,9 +54,9 @@ func (r *UserPost) GetMetadataPost(ctx context.Context, request *model.UserPostR
var total *int64
var err error

query.WriteString("SELECT COUNT(1) FROM userposts")
query.WriteString("SELECT COUNT(1) FROM user_posts")
query, params := querySelectParams(ctx, query, request)
query.WriteString("FROM userposts")
query.WriteString("FROM user_posts")
if ctx != nil {
err = r.conn.GetContext(ctx, total, query.String(), params...)
} else {
Expand All @@ -75,7 +75,7 @@ func (r *UserPost) GetListPostByMe(ctx context.Context, request *model.UserPostB
var result = make([]*model.PostResponse, 0)
var err error

query.WriteString("SELECT id, text, tags. image_path, images, last_user_post_comment_id, likes_count, comment_counts, status, created_by, updated_by, create_at, updated_at FROM userposts")
query.WriteString("SELECT id, text, tags. image_path, images, last_user_post_comment_id, likes_count, comments_count, status, created_by, updated_by, FROM_UNIXTIME(created_at) as created_at, FROM_UNIXTIME(updated_at) as updated_at FROM user_posts")
query, params := querySelectParams(ctx, query, request.UserPostRequest)
query.WriteString("AND created_by = ? ")
params = append(params, request.ActorID)
Expand All @@ -89,9 +89,9 @@ func (r *UserPost) GetListPostByMe(ctx context.Context, request *model.UserPostB
}

if ctx != nil {
err = r.conn.SelectContext(ctx, result, query.String(), params...)
err = r.conn.SelectContext(ctx, &result, query.String(), params...)
} else {
err = r.conn.Select(result, query.String(), params...)
err = r.conn.Select(&result, query.String(), params...)
}

if err != nil {
Expand All @@ -106,10 +106,10 @@ func (r *UserPost) GetMetadataPostByMe(ctx context.Context, request *model.UserP
var total *int64
var err error

query.WriteString("SELECT COUNT(1) FROM userposts")
query.WriteString("SELECT COUNT(1) FROM user_posts")
query, params := querySelectParams(ctx, query, request.UserPostRequest)
query.WriteString("AND created_by = ? ")
query.WriteString("FROM userposts")
query.WriteString("FROM user_posts")
params = append(params, request.ActorID)

if ctx != nil {
Expand Down Expand Up @@ -158,7 +158,7 @@ func (r *UserPost) GetDetailPost(ctx context.Context, id int64) (*model.PostResp
var result *model.PostResponse
var err error

query.WriteString("SELECT id, text, tags. image_path, images, last_user_post_comment_id, likes_count, comment_counts, status, created_by, updated_by, create_at, updated_at FROM userposts")
query.WriteString("SELECT id, text, tags, image_path, images, last_user_post_comment_id, likes_count, comments_count, status, created_by, updated_by, FROM_UNIXTIME(created_at) as created_at, FROM_UNIXTIME(updated_at) as updated_at FROM user_posts")
query.WriteString("WHERE id = ?")
if ctx != nil {
err = r.conn.GetContext(ctx, result, query.String(), id)
Expand Down Expand Up @@ -204,13 +204,12 @@ func (r *UserPost) CheckIsExistLikeOnPostBy(ctx context.Context, request *model.

func (r *UserPost) InsertPost(ctx context.Context, request *model.CreateNewPostRequestRepository) error {
var query bytes.Buffer
var params = make(map[string]interface{})
var err error
_, unixTime := helper.GetCurrentTimeUTC()

query.WriteString("INSERT INTO userposts (`text`, tags, image_path, images, status, created_by, updated_by, created_at, updated_at)")
query.WriteString("INSERT INTO user_posts (`text`, tags, image_path, images, status, created_by, updated_by, created_at, updated_at)")
query.WriteString("VALUES (:title, :tags, :image_path, :images, :status, :actor, :actor, :created_at, :created_at)")
params = map[string]interface{}{
params := map[string]interface{}{
"title": request.Title,
"tags": request.Tags,
"image_path": request.ImagePathURL,
Expand All @@ -234,13 +233,12 @@ func (r *UserPost) InsertPost(ctx context.Context, request *model.CreateNewPostR

func (r *UserPost) AddLikeOnPost(ctx context.Context, request *model.AddOrRemoveLikeOnPostRequest) error {
var query bytes.Buffer
var params = make(map[string]interface{})
var err error
_, unixTime := helper.GetCurrentTimeUTC()

query.WriteString("INSERT INTO likes (`type`, user_id, entity_id, created_at, updated_at) ")
query.WriteString("VALUES(:type_entity, :user_id, :entity_id, :current, :current)")
params = map[string]interface{}{
params := map[string]interface{}{
"type_entity": request.TypeEntity,
"user_id": request.ActorID,
"entity_id": request.UserPostID,
Expand All @@ -267,7 +265,7 @@ func (r *UserPost) UpdateStatusOrTitle(ctx context.Context, request *model.Updat
var err error
_, unixTime := helper.GetCurrentTimeUTC()

query.WriteString("UPDATE userposts")
query.WriteString("UPDATE user_posts")
if request.Status != nil {
query.WriteString("status` = :status")
params["status"] = request.Status
Expand Down Expand Up @@ -343,7 +341,6 @@ func querySelectParams(ctx context.Context, query bytes.Buffer, params *model.Us
query.WriteString(qBuffer.String())
query.WriteString(" status = ?")
queryParams = append(queryParams, params.Status)
first = false
}

return query, queryParams
Expand Down
Loading

0 comments on commit 1fcd148

Please sign in to comment.