/
service.go
61 lines (47 loc) · 1.16 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
package dextypes
import (
"context"
"github.com/go-pg/pg/v10"
"github.com/pkg/errors"
"github.com/pokedextracker/api.pokedextracker.com/pkg/errcodes"
)
type RetrieveDexTypeOptions struct {
ID *int
IncludeGameFamily bool
}
type Service struct {
db *pg.DB
}
func NewService(db *pg.DB) *Service {
return &Service{db}
}
func (svc *Service) RetrieveDexType(ctx context.Context, opts RetrieveDexTypeOptions) (*DexType, error) {
dexType := &DexType{}
q := svc.db.ModelContext(ctx, dexType)
if opts.ID != nil {
q = q.Where("dt.id = ?", *opts.ID)
}
if opts.IncludeGameFamily {
q = q.Relation("GameFamily")
}
err := q.Select()
if err != nil {
if errors.Is(err, pg.ErrNoRows) {
return nil, errcodes.NotFound("dex type")
}
return nil, errors.WithStack(err)
}
return dexType, nil
}
func (svc *Service) ListDexTypes(ctx context.Context) ([]*DexType, error) {
dexTypes := make([]*DexType, 0)
q := svc.db.
ModelContext(ctx, &dexTypes).
Join("INNER JOIN game_families gf ON dt.game_family_id = gf.id").
Order("gf.order DESC", "dt.order ASC")
err := q.Select()
if err != nil {
return nil, errors.WithStack(err)
}
return dexTypes, nil
}