SimpleCloudNotifier/server/api/models/channel.go

91 lines
2.6 KiB
Go
Raw Normal View History

2022-11-18 23:12:37 +01:00
package models
import (
"database/sql"
"github.com/blockloop/scan"
2022-11-19 12:47:23 +01:00
"gogs.mikescher.com/BlackForestBytes/goext/langext"
2022-11-18 23:12:37 +01:00
"time"
)
type Channel struct {
ChannelID int64
OwnerUserID int64
Name string
SubscribeKey string
SendKey string
TimestampCreated time.Time
TimestampLastRead *time.Time
TimestampLastSent *time.Time
MessagesSent int
}
func (c Channel) JSON() ChannelJSON {
return ChannelJSON{
ChannelID: c.ChannelID,
OwnerUserID: c.OwnerUserID,
Name: c.Name,
SubscribeKey: c.SubscribeKey,
SendKey: c.SendKey,
TimestampCreated: c.TimestampCreated.Format(time.RFC3339Nano),
TimestampLastRead: timeOptFmt(c.TimestampLastRead, time.RFC3339Nano),
TimestampLastSent: timeOptFmt(c.TimestampLastSent, time.RFC3339Nano),
MessagesSent: c.MessagesSent,
}
}
type ChannelJSON struct {
ChannelID int64 `json:"channel_id"`
OwnerUserID int64 `json:"owner_user_id"`
Name string `json:"name"`
SubscribeKey string `json:"subscribe_key"`
SendKey string `json:"send_key"`
TimestampCreated string `json:"timestamp_created"`
TimestampLastRead *string `json:"timestamp_last_read"`
TimestampLastSent *string `json:"timestamp_last_sent"`
MessagesSent int `json:"messages_sent"`
}
type ChannelDB struct {
ChannelID int64 `db:"channel_id"`
OwnerUserID int64 `db:"owner_user_id"`
Name string `db:"name"`
SubscribeKey string `db:"subscribe_key"`
SendKey string `db:"send_key"`
TimestampCreated int64 `db:"timestamp_created"`
TimestampLastRead *int64 `db:"timestamp_last_read"`
TimestampLastSent *int64 `db:"timestamp_last_sent"`
MessagesSent int `db:"messages_sent"`
}
func (c ChannelDB) Model() Channel {
return Channel{
ChannelID: c.ChannelID,
OwnerUserID: c.OwnerUserID,
Name: c.Name,
SubscribeKey: c.SubscribeKey,
SendKey: c.SendKey,
TimestampCreated: time.UnixMilli(c.TimestampCreated),
TimestampLastRead: timeOptFromMilli(c.TimestampLastRead),
TimestampLastSent: timeOptFromMilli(c.TimestampLastSent),
MessagesSent: c.MessagesSent,
}
}
func DecodeChannel(r *sql.Rows) (Channel, error) {
2022-11-19 12:47:23 +01:00
var data ChannelDB
err := scan.RowStrict(&data, r)
2022-11-18 23:12:37 +01:00
if err != nil {
return Channel{}, err
}
2022-11-19 12:47:23 +01:00
return data.Model(), nil
}
func DecodeChannels(r *sql.Rows) ([]Channel, error) {
var data []ChannelDB
err := scan.RowsStrict(&data, r)
if err != nil {
return nil, err
}
return langext.ArrMap(data, func(v ChannelDB) Channel { return v.Model() }), nil
2022-11-18 23:12:37 +01:00
}