reprogl
125 строк · 2.2 Кб
1package repositories
2
3import (
4"database/sql"
5"errors"
6"time"
7
8"xelbot.com/reprogl/models"
9)
10
11type EmailSubscriptionRepository struct {
12DB *sql.DB
13}
14
15func (es *EmailSubscriptionRepository) Find(id int) (*models.EmailSubscription, error) {
16query := `
17SELECT
18s.id,
19s.email,
20s.subs_type,
21s.block_sending
22FROM subscription_settings AS s
23WHERE s.id = ?`
24
25model := models.EmailSubscription{}
26err := es.DB.QueryRow(query, id).Scan(
27&model.ID,
28&model.Email,
29&model.Type,
30&model.BlockSending)
31
32if err != nil {
33if errors.Is(err, sql.ErrNoRows) {
34return nil, models.RecordNotFound
35} else {
36return nil, err
37}
38}
39
40return &model, nil
41}
42
43func (es *EmailSubscriptionRepository) FindOrCreate(email string, subscrType int) (*models.EmailSubscription, error) {
44query := `
45SELECT
46s.id,
47s.email,
48s.subs_type,
49s.block_sending
50FROM subscription_settings AS s
51WHERE
52s.email = ?
53AND s.subs_type = ?`
54
55model := models.EmailSubscription{}
56err := es.DB.QueryRow(query, email, subscrType).Scan(
57&model.ID,
58&model.Email,
59&model.Type,
60&model.BlockSending)
61
62if err != nil {
63if errors.Is(err, sql.ErrNoRows) {
64return es.Create(email, subscrType)
65} else {
66return nil, err
67}
68}
69
70return &model, nil
71}
72
73func (es *EmailSubscriptionRepository) Create(email string, subscrType int) (*models.EmailSubscription, error) {
74query := `INSERT INTO subscription_settings (email, subs_type, block_sending)
75VALUES (?, ?, ?)`
76
77stmtResult, err := es.DB.Exec(
78query,
79email,
80subscrType,
810,
82)
83if err != nil {
84return nil, err
85}
86
87id, err := stmtResult.LastInsertId()
88if err != nil {
89return nil, err
90}
91
92return &models.EmailSubscription{
93ID: int(id),
94Email: email,
95Type: subscrType,
96}, nil
97}
98
99func (es *EmailSubscriptionRepository) Unsubscribe(id int) error {
100return es.changeBlockSending(id, 1)
101}
102
103func (es *EmailSubscriptionRepository) Subscribe(id int) error {
104return es.changeBlockSending(id, 0)
105}
106
107func (es *EmailSubscriptionRepository) changeBlockSending(id, value int) error {
108query := `
109UPDATE
110subscription_settings
111SET
112block_sending = ?,
113last_update = ?
114WHERE
115id = ?`
116
117_, err := es.DB.Exec(
118query,
119value,
120time.Now().Format("2006-01-02 15:04:05.000"),
121id,
122)
123
124return err
125}
126