apollo-backend/internal/data/devices.go

70 lines
1.3 KiB
Go
Raw Normal View History

2021-05-10 00:51:15 +00:00
package data
import (
2021-07-13 14:17:20 +00:00
"context"
2021-05-10 00:51:15 +00:00
"time"
2021-07-13 14:17:20 +00:00
"github.com/jackc/pgx/v4"
"github.com/jackc/pgx/v4/pgxpool"
2021-05-10 00:51:15 +00:00
)
type Device struct {
ID int64
APNSToken string
Sandbox bool
LastPingedAt int64
}
type DeviceModel struct {
2021-07-13 14:17:20 +00:00
ctx context.Context
pool *pgxpool.Pool
2021-05-10 00:51:15 +00:00
}
func (dm *DeviceModel) Upsert(d *Device) error {
d.LastPingedAt = time.Now().Unix()
2021-07-13 14:17:20 +00:00
return dm.pool.BeginFunc(dm.ctx, func(tx pgx.Tx) error {
stmt := `
INSERT INTO devices (apns_token, sandbox, last_pinged_at)
VALUES ($1, $2, $3)
ON CONFLICT(apns_token)
DO
UPDATE SET last_pinged_at = $3
RETURNING id`
return tx.QueryRow(
dm.ctx,
stmt,
d.APNSToken,
d.Sandbox,
d.LastPingedAt,
).Scan(&d.ID)
})
2021-05-10 00:51:15 +00:00
}
func (dm *DeviceModel) GetByAPNSToken(token string) (*Device, error) {
2021-07-13 14:17:20 +00:00
device := &Device{}
stmt := `
2021-05-10 00:51:15 +00:00
SELECT id, apns_token, sandbox, last_pinged_at
FROM devices
WHERE apns_token = $1`
2021-07-13 14:17:20 +00:00
if err := dm.pool.QueryRow(dm.ctx, stmt, token).Scan(
2021-05-10 00:51:15 +00:00
&device.ID,
&device.APNSToken,
&device.Sandbox,
&device.LastPingedAt,
2021-07-13 14:17:20 +00:00
); err != nil {
return nil, err
2021-05-10 00:51:15 +00:00
}
return device, nil
}
type MockDeviceModel struct{}
func (mdm *MockDeviceModel) Upsert(d *Device) error {
return nil
}
func (mdm *MockDeviceModel) GetByAPNSToken(token string) (*Device, error) {
return nil, nil
}