forked from microservices-demo/catalogue
-
Notifications
You must be signed in to change notification settings - Fork 0
/
service.go
223 lines (181 loc) · 5.48 KB
/
service.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
package catalogue
// service.go contains the definition and implementation (business logic) of the
// catalogue service. Everything here is agnostic to the transport (HTTP).
import (
"errors"
"strings"
"time"
"github.com/go-kit/kit/log"
"github.com/jmoiron/sqlx"
)
// Service is the catalogue service, providing read operations on a saleable
// catalogue of sock products.
type Service interface {
List(tags []string, order string, pageNum, pageSize int) ([]Sock, error) // GET /catalogue
Count(tags []string) (int, error) // GET /catalogue/size
Get(id string) (Sock, error) // GET /catalogue/{id}
Tags() ([]string, error) // GET /tags
Health() []Health // GET /health
}
// Middleware decorates a Service.
type Middleware func(Service) Service
// Sock describes the thing on offer in the catalogue.
type Sock struct {
ID string `json:"id" db:"id"`
Name string `json:"name" db:"name"`
Description string `json:"description" db:"description"`
ImageURL []string `json:"imageUrl" db:"-"`
ImageURL_1 string `json:"-" db:"image_url_1"`
ImageURL_2 string `json:"-" db:"image_url_2"`
Price float32 `json:"price" db:"price"`
Count int `json:"count" db:"count"`
Tags []string `json:"tag" db:"-"`
TagString string `json:"-" db:"tag_name"`
}
// Health describes the health of a service
type Health struct {
Service string `json:"service"`
Status string `json:"status"`
Time string `json:"time"`
}
// ErrNotFound is returned when there is no sock for a given ID.
var ErrNotFound = errors.New("not found")
// ErrDBConnection is returned when connection with the database fails.
var ErrDBConnection = errors.New("database connection error")
var baseQuery = "SELECT sock.sock_id AS id, sock.name, sock.description, sock.price, sock.count, sock.image_url_1, sock.image_url_2, GROUP_CONCAT(tag.name) AS tag_name FROM sock JOIN sock_tag ON sock.sock_id=sock_tag.sock_id JOIN tag ON sock_tag.tag_id=tag.tag_id"
// NewCatalogueService returns an implementation of the Service interface,
// with connection to an SQL database.
func NewCatalogueService(db *sqlx.DB, logger log.Logger) Service {
return &catalogueService{
db: db,
logger: logger,
}
}
type catalogueService struct {
db *sqlx.DB
logger log.Logger
}
func (s *catalogueService) List(tags []string, order string, pageNum, pageSize int) ([]Sock, error) {
var socks []Sock
query := baseQuery
var args []interface{}
for i, t := range tags {
if i == 0 {
query += " WHERE tag.name=?"
args = append(args, t)
} else {
query += " OR tag.name=?"
args = append(args, t)
}
}
query += " GROUP BY id"
if order != "" {
query += " ORDER BY ?"
args = append(args, order)
}
query += ";"
err := s.db.Select(&socks, query, args...)
if err != nil {
s.logger.Log("database error", err)
return []Sock{}, ErrDBConnection
}
for i, s := range socks {
socks[i].ImageURL = []string{s.ImageURL_1, s.ImageURL_2}
socks[i].Tags = strings.Split(s.TagString, ",")
}
socks = cut(socks, pageNum, pageSize)
return socks, nil
}
func (s *catalogueService) Count(tags []string) (int, error) {
query := "SELECT COUNT(DISTINCT sock.sock_id) FROM sock JOIN sock_tag ON sock.sock_id=sock_tag.sock_id JOIN tag ON sock_tag.tag_id=tag.tag_id"
var args []interface{}
for i, t := range tags {
if i == 0 {
query += " WHERE tag.name=?"
args = append(args, t)
} else {
query += " OR tag.name=?"
args = append(args, t)
}
}
query += ";"
sel, err := s.db.Prepare(query)
if err != nil {
s.logger.Log("database error", err)
return 0, ErrDBConnection
}
defer sel.Close()
var count int
err = sel.QueryRow(args...).Scan(&count)
if err != nil {
s.logger.Log("database error", err)
return 0, ErrDBConnection
}
return count, nil
}
func (s *catalogueService) Get(id string) (Sock, error) {
query := baseQuery + " WHERE sock.sock_id =? GROUP BY sock.sock_id;"
var sock Sock
err := s.db.Get(&sock, query, id)
if err != nil {
s.logger.Log("database error", err)
return Sock{}, ErrNotFound
}
sock.ImageURL = []string{sock.ImageURL_1, sock.ImageURL_2}
sock.Tags = strings.Split(sock.TagString, ",")
return sock, nil
}
func (s *catalogueService) Health() []Health {
var health []Health
dbstatus := "OK"
err := s.db.Ping()
if err != nil {
dbstatus = "err"
}
app := Health{"catalogue", "OK", time.Now().String()}
db := Health{"catalogue-db", dbstatus, time.Now().String()}
health = append(health, app)
health = append(health, db)
return health
}
func (s *catalogueService) Tags() ([]string, error) {
var tags []string
query := "SELECT name FROM tag;"
rows, err := s.db.Query(query)
if err != nil {
s.logger.Log("database error", err)
return []string{}, ErrDBConnection
}
var tag string
for rows.Next() {
err = rows.Scan(&tag)
if err != nil {
s.logger.Log("database error", err)
continue
}
tags = append(tags, tag)
}
return tags, nil
}
func cut(socks []Sock, pageNum, pageSize int) []Sock {
if pageNum == 0 || pageSize == 0 {
return []Sock{} // pageNum is 1-indexed
}
start := (pageNum * pageSize) - pageSize
if start > len(socks) {
return []Sock{}
}
end := (pageNum * pageSize)
if end > len(socks) {
end = len(socks)
}
return socks[start:end]
}
func contains(s []string, e string) bool {
for _, a := range s {
if a == e {
return true
}
}
return false
}