This repository has been archived by the owner on Sep 16, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
genres.go
95 lines (74 loc) · 1.98 KB
/
genres.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
package models
import (
"context"
"database/sql"
"errors"
"time"
)
// Genre type is a struct for genres table.
type Genre struct {
ID int64 `json:"id"`
Name string `json:"name" validate:"required"`
CreatedAt time.Time `db:"created_at" json:"created_at"`
UpdatedAt time.Time `db:"updated_at" json:"updated_at"`
}
// GenreResult type is a result slice for genres.
type GenreResult struct {
Data *[]Genre `json:"data"`
}
// GetGenres retrieves the latest genres.
func (c *Conn) GetGenres(ctx context.Context, limit int) (*GenreResult, error) {
var result []Genre
err := c.db.SelectContext(ctx, &result, queryGenresSelect, limit)
if err != nil && err != sql.ErrNoRows {
return nil, err
}
return &GenreResult{&result}, nil
}
// GetGenre retrieves a genre by ID.
func (c *Conn) GetGenre(ctx context.Context, id int64) (*Genre, error) {
var genre Genre
err := c.db.GetContext(ctx, &genre, queryGenreSelectByID, id)
if err != nil && err != sql.ErrNoRows {
return nil, err
}
return &genre, nil
}
// CreateGenre creates a new genre.
func (c *Conn) CreateGenre(ctx context.Context, g *Genre) error {
_, err := c.db.ExecContext(ctx, queryGenreInsert, g.Name, g.CreatedAt, g.UpdatedAt)
if err != nil {
return err
}
return nil
}
// UpdateGenre updates a genre by ID.
func (c *Conn) UpdateGenre(ctx context.Context, id int64, g *Genre) error {
result, err := c.db.ExecContext(ctx, queryGenreUpdate, g.Name, g.UpdatedAt, id)
if err != nil {
return err
}
rowsAffected, err := result.RowsAffected()
if err != nil {
return err
}
if rowsAffected == 0 {
return errors.New(errResourceNotFound)
}
return nil
}
// DeleteGenre deletes a genre by ID.
func (c *Conn) DeleteGenre(ctx context.Context, id int64) error {
result, err := c.db.ExecContext(ctx, queryGenreDelete, id)
if err != nil {
return err
}
rowsAffected, err := result.RowsAffected()
if err != nil {
return err
}
if rowsAffected == 0 {
return errors.New(errResourceNotFound)
}
return nil
}