Skip to content

Commit 8131382

Browse files
Rodrigo Dos SantosRodrigo Dos Santos
authored andcommitted
Fix go integration with kotlin - build go-service, build kotlin-service
1 parent 5ad4d45 commit 8131382

File tree

11 files changed

+134
-459
lines changed

11 files changed

+134
-459
lines changed

go-service/.env

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@ JAEGER_SERVICE_NAME = go-service
1414

1515
HOSTNAME = localhost
1616

17-
TASKS_API_URL = http://task-api:8084/api/tasks
17+
TASKS_API_URL = http://localhost:8083/api/tasks
1818

19-
LOAD_DEFAULT_VALUES = true
19+
LOAD_DEFAULT_VALUES = true
20+
21+
CALL_TASK_API = false

go-service/.env.docker

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,4 +18,6 @@ HOSTNAME = go-service
1818

1919
TASKS_API_URL = http://task-api:8084/api/tasks
2020

21-
LOAD_DEFAULT_VALUES = true
21+
LOAD_DEFAULT_VALUES = true
22+
23+
CALL_TASK_API = false

go-service/.env.production

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,4 +16,6 @@ HOSTNAME = go-service
1616

1717
TASKS_API_URL = https://spendingbetter.com/api/tasks
1818

19-
LOAD_DEFAULT_VALUES = false
19+
LOAD_DEFAULT_VALUES = false
20+
21+
CALL_TASK_API = false

go-service/go.mod

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,17 +3,26 @@ module go-service
33
go 1.15
44

55
require (
6+
github.com/aws/aws-sdk-go v1.42.34 // indirect
67
github.com/dgrijalva/jwt-go v3.2.0+incompatible
78
github.com/go-playground/validator/v10 v10.4.0
8-
github.com/hashicorp/consul v1.13.1
9+
github.com/gogo/protobuf v1.3.2 // indirect
10+
github.com/google/gofuzz v1.2.0 // indirect
911
github.com/hashicorp/consul/api v1.14.0
12+
github.com/hashicorp/consul/sdk v0.11.0 // indirect
13+
github.com/hashicorp/serf v0.9.8 // indirect
1014
github.com/joho/godotenv v1.3.0
1115
github.com/labstack/echo-contrib v0.9.0
1216
github.com/labstack/echo/v4 v4.1.17
1317
github.com/labstack/gommon v0.3.0
18+
github.com/oliveagle/jsonpath v0.0.0-20180606110733-2e52cf6e6852
1419
github.com/prometheus/client_golang v1.7.1 // indirect
20+
github.com/yalp/jsonpath v0.0.0-20180802001716-5cc68e5049a0 // indirect
1521
go.mongodb.org/mongo-driver v1.4.1
22+
golang.org/x/crypto v0.0.0-20210513164829-c07d793c2f9a // indirect
1623
golang.org/x/time v0.0.0-20201208040808-7e3f01d25324 // indirect
24+
google.golang.org/appengine v1.6.6 // indirect
25+
google.golang.org/protobuf v1.27.1 // indirect
1726
gopkg.in/yaml.v2 v2.2.8
1827
k8s.io/api v0.20.1 // indirect
1928
k8s.io/apimachinery v0.20.1

go-service/go.sum

Lines changed: 4 additions & 426 deletions
Large diffs are not rendered by default.

go-service/posts-api/main.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -179,7 +179,7 @@ func processRestApi(middlewareObj echo.MiddlewareFunc) {
179179
e.Logger.SetLevel(log.DEBUG)
180180
e.GET("/api/posts", rest.GetAllPosts, middlewareObj, rest.HasValidReadPermission)
181181
e.POST("/api/posts", rest.CreatePost, middlewareObj, rest.HasValidCreatePermission)
182-
e.GET("/api/posts/:id", rest.GetPost, middlewareObj, rest.HasValidReadPermission)
182+
e.GET("/api/posts/:id", rest.GetPostById, middlewareObj, rest.HasValidReadPermission)
183183
e.PUT("/api/posts/:id", rest.UpdatePost, middlewareObj, rest.HasValidSavePermission)
184184
e.DELETE("/api/posts/:id", rest.DeletePost, middlewareObj, rest.HasValidDeletePermission)
185185
e.GET("/actuator/info", healthCheck)

go-service/posts-api/rest/rest.go

Lines changed: 92 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package rest
22

33
import (
44
"context"
5+
"encoding/json"
56
"fmt"
67
"github.com/dgrijalva/jwt-go"
78
"github.com/labstack/echo/v4"
@@ -12,15 +13,17 @@ import (
1213
"go.mongodb.org/mongo-driver/bson/primitive"
1314
"go.mongodb.org/mongo-driver/mongo"
1415
"go.mongodb.org/mongo-driver/mongo/options"
15-
"io/ioutil"
16-
"k8s.io/apimachinery/pkg/util/json"
16+
"math"
1717
"net/http"
18+
"strconv"
19+
"strings"
1820
"time"
1921
)
2022

2123
var (
2224
client = connectMongo()
2325
collection = client.Database(util.GetEnv("MONGODB_DATABASE")).Collection("posts")
26+
httpClient = &http.Client{Timeout: 2 * time.Second}
2427
)
2528

2629
func connectMongo() *mongo.Client {
@@ -129,48 +132,83 @@ func CreateDefaultPosts() {
129132
}
130133
}
131134

132-
func GetTasksApi(c echo.Context) []model.Task {
135+
func GetTasksApi(c echo.Context, id string) []model.TaskDto {
133136
authorizationHeader := c.Request().Header.Get("Authorization")
134137

135-
req, err := http.NewRequest("GET", util.GetEnv("TASKS_API_URL"), nil)
138+
req, err := http.NewRequest("GET", util.GetEnv("TASKS_API_URL")+"?postId="+id, nil)
136139
req.Header.Add("Authorization", authorizationHeader)
137140

138-
client := &http.Client{}
139-
resp, err := client.Do(req)
141+
resp, err := httpClient.Do(req)
140142
if err != nil {
141143
log.Warn(fmt.Sprintf("Error Task Api Connection = %v", err))
142144
return nil
143145
}
144146
defer resp.Body.Close()
145-
body, err := ioutil.ReadAll(resp.Body)
147+
var taskDto model.PageTaskDto
148+
err = json.NewDecoder(resp.Body).Decode(&taskDto)
146149
if err != nil {
147150
log.Warn(fmt.Sprintf("Error Read Task Api = %v", err))
148151
return nil
149152
}
150-
var tasks []model.Task
151-
if err := json.Unmarshal(body, &tasks); err != nil {
152-
log.Warn(fmt.Sprintf("Error Parse Task Api Response = %v", err))
153-
return nil
154-
}
155-
156-
return tasks
153+
return taskDto.Task
157154
}
158155

159156
func GetAllPosts(c echo.Context) error {
157+
page := 0
158+
size := 10
159+
if c := c.QueryParam("page"); c != "" {
160+
page, _ = strconv.Atoi(c)
161+
}
162+
if c := c.QueryParam("size"); c != "" {
163+
size, _ = strconv.Atoi(c)
164+
}
165+
var searchByText string
166+
if strings.Contains(c.QueryString(), "&") {
167+
searchByText = c.QueryString()
168+
searchByText = searchByText[0:strings.Index(searchByText, "&")]
169+
}
170+
log.Info(fmt.Sprintf("QueryString = %v", searchByText))
171+
pageInt64 := int64(page)
172+
sizeInt64 := int64(size)
160173
ctx := context.TODO()
161-
var posts []*model.Post
174+
pagination := new(model.Pagination)
175+
pagination.Page = pageInt64
176+
pagination.Size = sizeInt64
177+
var posts []model.PostDto
162178
var cur *mongo.Cursor
163-
opts := options.Find().SetSort(bson.D{{"createdDate", 1}})
179+
opts := options.Find().SetSort(bson.D{{"createdDate", 1}}).SetSkip(pageInt64).SetLimit(sizeInt64)
164180

165181
if isAdmin(c) {
166-
cursor, err := collection.Find(ctx, bson.D{}, opts)
182+
filter := bson.M{}
183+
if searchByText != "" {
184+
filter = bson.M{
185+
"name": bson.D{{"$all", bson.A{searchByText}}},
186+
}
187+
}
188+
count, err2 := collection.CountDocuments(ctx, filter)
189+
if err2 != nil {
190+
return err2
191+
}
192+
pagination.TotalElements = count
193+
cursor, err := collection.Find(ctx, filter, opts)
167194
if err != nil {
168195
return err
169196
}
170197
cur = cursor
171198
} else {
172199
createdByUser := getAuthUser(c)["sub"].(string)
173200
filter := bson.M{"createdByUser": createdByUser}
201+
if searchByText != "" {
202+
filter = bson.M{
203+
"createdByUser": createdByUser,
204+
"name": bson.D{{"$all", bson.A{searchByText}}},
205+
}
206+
}
207+
count, err2 := collection.CountDocuments(ctx, filter)
208+
if err2 != nil {
209+
return err2
210+
}
211+
pagination.TotalElements = count
174212

175213
cursor, err := collection.Find(ctx, filter, opts)
176214

@@ -185,12 +223,36 @@ func GetAllPosts(c echo.Context) error {
185223
if err := cur.Decode(&post); err != nil {
186224
return err
187225
}
226+
if post.LastModifiedDate != nil && post.LastModifiedDate.IsZero() {
227+
post.LastModifiedDate = nil
228+
}
229+
postDto := model.PostDto{
230+
ID: post.ID.Hex(),
231+
Name: post.Name,
232+
CreatedDate: post.CreatedDate.String(),
233+
CreatedByUser: post.CreatedByUser,
234+
LastModifiedByUser: post.LastModifiedByUser,
235+
}
188236
if util.GetEnvAsBool("CALL_TASK_API") {
189-
post.Tasks = GetTasksApi(c)
237+
postDto.Tasks = GetTasksApi(c, postDto.ID)
190238
}
191-
posts = append(posts, &post)
239+
if post.LastModifiedDate != nil && !post.LastModifiedDate.IsZero() {
240+
postDto.LastModifiedDate = post.LastModifiedDate.String()
241+
}
242+
posts = append(posts, postDto)
243+
}
244+
pagination.Post = append(posts)
245+
if pagination.Post == nil {
246+
pagination.Post = []model.PostDto{}
192247
}
193-
return c.JSON(http.StatusOK, posts)
248+
249+
if pagination.TotalPages > sizeInt64 {
250+
pagination.TotalPages = int64(math.Ceil(float64(pagination.TotalElements / sizeInt64)))
251+
} else {
252+
pagination.TotalPages = 1
253+
}
254+
255+
return c.JSON(http.StatusOK, pagination)
194256
}
195257

196258
func CreatePost(c echo.Context) error {
@@ -211,7 +273,7 @@ func CreatePost(c echo.Context) error {
211273
return c.JSON(http.StatusCreated, u)
212274
}
213275

214-
func GetPost(c echo.Context) error {
276+
func GetPostById(c echo.Context) error {
215277
id := c.Param("id")
216278
if "" == id {
217279
panic("Id is mandatory!")
@@ -254,17 +316,22 @@ func UpdatePost(c echo.Context) error {
254316
return echo.NewHTTPError(http.StatusNotFound, fmt.Sprintf("Not found ID: %v", id))
255317
}
256318

257-
u := new(model.Post)
319+
u := new(model.PostDto)
258320
if err := c.Bind(u); err != nil {
259321
return err
260322
}
261323
if err := c.Validate(u); err != nil {
262324
return err
263325
}
264326

265-
u.LastModifiedDate = time.Now()
266-
u.LastModifiedByUser = getAuthUser(c)["sub"].(string)
267-
if _, err := collection.UpdateOne(ctx, filter, u); err != nil {
327+
var t = time.Now()
328+
post.Name = u.Name
329+
post.LastModifiedDate = &t
330+
post.LastModifiedByUser = getAuthUser(c)["sub"].(string)
331+
update := bson.M{
332+
"$set": post,
333+
}
334+
if _, err := collection.UpdateOne(ctx, filter, update); err != nil {
268335
return err
269336
}
270337
return c.JSON(http.StatusOK, u)

kotlin-service/src/main/kotlin/com/microservice/kotlin/config/ServiceConfiguration.kt

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import org.springframework.boot.CommandLineRunner
1212
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean
1313
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty
1414
import org.springframework.boot.info.BuildProperties
15+
import org.springframework.boot.info.GitProperties
1516
import org.springframework.context.annotation.Bean
1617
import org.springframework.context.annotation.Configuration
1718
import org.springframework.context.annotation.Primary
@@ -49,6 +50,12 @@ class ServiceConfiguration {
4950
@ConditionalOnMissingBean
5051
fun buildProperties(): BuildProperties = BuildProperties(Properties())
5152

53+
@ConditionalOnMissingBean
54+
@Bean
55+
fun gitProperties(): GitProperties? {
56+
return GitProperties(Properties())
57+
}
58+
5259
@ConditionalOnProperty(prefix = "load.data", name = ["tasks"], havingValue = "true")
5360
@Bean
5461
fun runner(

kotlin-service/src/main/kotlin/com/microservice/kotlin/controller/TaskController.kt

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,11 +49,15 @@ class TaskController(@Autowired val repository: TaskRepository) {
4949
@RequestParam(name = "sort-dir", defaultValue = "desc", required = false) sortDirection: String,
5050
@RequestParam(name = "sort-idx", defaultValue = "createdDate", required = false) sortIdx: List<String>,
5151
@QuerydslPredicate(root = Task::class, bindings = TaskRepository::class) predicate: Predicate,
52-
@Parameter(hidden = true) authentication: Authentication): ResponseEntity<Page<Task>> {
52+
@Parameter(hidden = true) authentication: Authentication,
53+
@RequestParam(required = false, name = "postId") postId: String?): ResponseEntity<Page<Task>> {
5354
log.debug("Predicate: {}", predicate)
55+
log.debug("PostId: {}", postId)
5456
val pageRequest = PageRequest.of(page, size, Sort.by(Sort.Direction.fromString(sortDirection), *sortIdx.toTypedArray()))
5557
return if (authentication.hasAdminAuthority()) {
5658
ResponseEntity.ok(repository.findAll(predicate, pageRequest))
59+
} else if (postId != null) {
60+
ResponseEntity.ok(repository.findAllByCreatedByUserAndPostId(authentication.name, postId, pageRequest))
5761
} else {
5862
ResponseEntity.ok(repository.findAllByCreatedByUser(authentication.name, pageRequest))
5963
}

kotlin-service/src/main/kotlin/com/microservice/kotlin/model/Task.kt

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,5 +25,7 @@ data class Task(
2525
var lastModifiedByUser: String? = null,
2626

2727
@LastModifiedDate
28-
var lastModifiedDate: Instant? = null
28+
var lastModifiedDate: Instant? = null,
29+
30+
var postId: String? = null
2931
)

0 commit comments

Comments
 (0)