63 lines
1.2 KiB
Go
63 lines
1.2 KiB
Go
package plan
|
|
|
|
import (
|
|
"errors"
|
|
"time"
|
|
|
|
"gorm.io/gorm"
|
|
v1 "pkg.bing89.com/travebing/api/v1"
|
|
"pkg.bing89.com/travebing/tberror"
|
|
)
|
|
|
|
type Controller interface {
|
|
List() ([]v1.TravelPlan, int, error)
|
|
Get(id int)(*v1.TravelPlan, int, error)
|
|
Create(opt CreateOption) (*v1.TravelPlan, int, error)
|
|
}
|
|
|
|
type plan struct {
|
|
db *gorm.DB
|
|
}
|
|
|
|
func New(db *gorm.DB) Controller {
|
|
p := &plan{
|
|
db: db,
|
|
}
|
|
return p
|
|
}
|
|
|
|
func (c *plan) List() ([]v1.TravelPlan, int, error) {
|
|
ret := []v1.TravelPlan{}
|
|
err := c.db.Find(&ret).Error
|
|
if err != nil {
|
|
return ret, tberror.CodeDatabase, err
|
|
}
|
|
return ret, 0, nil
|
|
}
|
|
|
|
func (c *plan) Create(opt CreateOption) (*v1.TravelPlan, int, error) {
|
|
if opt.Validate() {
|
|
return nil, tberror.CodeInvalidArgs, errors.New("invalid args")
|
|
}
|
|
ret := &v1.TravelPlan{
|
|
Name: opt.Name,
|
|
ArriveTo: opt.Arrive,
|
|
LeaveFrom: opt.Leave,
|
|
CreatedAt: time.Now().Unix(),
|
|
}
|
|
err := c.db.Create(ret).Error
|
|
if err != nil {
|
|
return nil, tberror.CodeDatabase, err
|
|
}
|
|
|
|
return ret, 0, nil
|
|
}
|
|
|
|
func (c *plan)Get(id int)(*v1.TravelPlan, int, error) {
|
|
ret := &v1.TravelPlan{}
|
|
err := c.db.Where("id = ?", id).First(ret).Error
|
|
if err != nil {
|
|
return ret, tberror.CodeDatabase, err
|
|
}
|
|
return ret, 0, nil
|
|
} |