dorisbot/models/public/facebook.go
2019-07-13 17:44:31 +08:00

100 lines
2.2 KiB
Go

package public
import (
"database/sql"
"dorisbot/models"
"errors"
"time"
)
// FacebookPageModel -
type FacebookPageModel struct {
ID string `db:"id"`
LastPost string `db:"lastpost"`
Ctime time.Time `db:"ctime"`
Mtime time.Time `db:"mtime"`
}
// NewFacebookPage -
func NewFacebookPage(id string) (page *FacebookPageModel, err error) {
if len(id) == 0 {
return nil, errors.New("id is empty")
}
page = &FacebookPageModel{
ID: id,
}
return
}
// GetFacebookPageByID -
func GetFacebookPageByID(id string) (page *FacebookPageModel, err error) {
if len(id) == 0 {
return nil, errors.New("id is empty")
}
page = &FacebookPageModel{}
db := models.GetConn()
query := `select id, lastpost, ctime, mtime from public.facebook_page where id = $1`
err = db.Get(page, query, id)
if err != nil {
return
}
return
}
// GetAllFacebookPage -
func GetAllFacebookPage() (pages []*FacebookPageModel, err error) {
db := models.GetConn()
query := `select id, lastpost, ctime, mtime from public.facebook_page order by ctime`
err = db.Select(&pages, query)
if err != nil && err == sql.ErrNoRows {
return nil, nil
}
return
}
// GetFacebookPageRange -
func GetFacebookPageRange(limit, offset int) (pages []*FacebookPageModel, err error) {
if limit < 1 || offset < 0 {
return nil, errors.New("input arg format error")
}
db := models.GetConn()
query := `select id, lastpost, ctime, mtime from public.facebook_page order by ctime limit $1 offset $2`
err = db.Select(&pages, query, limit, offset)
if err != nil && err == sql.ErrNoRows {
return nil, nil
}
return
}
// Write -
func (p *FacebookPageModel) Write() (err error) {
db := models.GetConn()
query := `insert into public.facebook_page (id) values (:id) returning *`
rows, err := db.NamedQuery(query, p)
if err != nil {
return err
}
defer rows.Close()
if rows.Next() {
err = rows.StructScan(p)
if err != nil {
return err
}
}
return
}
// UpdatePost -
func (p *FacebookPageModel) UpdatePost(post string) (err error) {
db := models.GetConn()
query := `update public.facebook_page set lastpost = $1, mtime = now() where id = $2`
_, err = db.Exec(query, post, p.ID)
if err != nil {
return err
}
p.LastPost = post
return
}