Cache chats, simplify errors.
This commit is contained in:
parent
49fed21990
commit
e90dd53bae
1 changed files with 13 additions and 5 deletions
|
|
@ -17,13 +17,17 @@ type Chat struct {
|
|||
type ChatModel struct {
|
||||
ctx context.Context
|
||||
db *sqlx.DB
|
||||
|
||||
// Cached on first ListChats().
|
||||
chats []*Chat
|
||||
}
|
||||
|
||||
func NewChatModel(ctx context.Context, db *sqlx.DB) *ChatModel {
|
||||
return &ChatModel{ctx, db}
|
||||
return &ChatModel{ctx, db, nil}
|
||||
}
|
||||
|
||||
func (cm *ChatModel) AddChat(id int, name string) (chat *Chat, err error) {
|
||||
cm.chats = nil
|
||||
chat = &Chat{}
|
||||
err = cm.db.GetContext(cm.ctx, chat,
|
||||
`insert into chats (id, name) values (?, ?)`, id, name)
|
||||
|
|
@ -31,8 +35,7 @@ func (cm *ChatModel) AddChat(id int, name string) (chat *Chat, err error) {
|
|||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return chat, nil
|
||||
}
|
||||
var serr sqlite3.Error
|
||||
if errors.As(err, &serr) {
|
||||
if serr, ok := errors.AsType[sqlite3.Error](err); ok {
|
||||
switch serr.ExtendedCode {
|
||||
case sqlite3.ErrConstraintUnique, sqlite3.ErrConstraintPrimaryKey:
|
||||
return nil, ErrUniqueConstraint.Do(err)
|
||||
|
|
@ -44,15 +47,19 @@ func (cm *ChatModel) AddChat(id int, name string) (chat *Chat, err error) {
|
|||
}
|
||||
|
||||
func (cm *ChatModel) ListChats() ([]*Chat, error) {
|
||||
if cm.chats != nil {
|
||||
return cm.chats, nil
|
||||
}
|
||||
|
||||
var chats []*Chat
|
||||
err := cm.db.GetContext(cm.ctx, chats,
|
||||
`select id, name from chats where id < 0`)
|
||||
if err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
cm.chats = chats
|
||||
return chats, nil
|
||||
}
|
||||
var serr sqlite3.Error
|
||||
if errors.As(err, &serr) {
|
||||
if serr, ok := errors.AsType[sqlite3.Error](err); ok {
|
||||
switch serr.ExtendedCode {
|
||||
case sqlite3.ErrConstraintUnique, sqlite3.ErrConstraintPrimaryKey:
|
||||
return nil, ErrUniqueConstraint.Do(err)
|
||||
|
|
@ -60,5 +67,6 @@ func (cm *ChatModel) ListChats() ([]*Chat, error) {
|
|||
}
|
||||
return nil, err
|
||||
}
|
||||
cm.chats = chats
|
||||
return chats, nil
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue