blog_backend_api/model/hardware.go

108 lines
2.4 KiB
Go
Raw Normal View History

package model
2020-03-25 02:57:25 +00:00
import (
"background/db"
2020-03-27 16:00:46 +00:00
"background/utils"
2020-03-25 02:57:25 +00:00
"github.com/pkg/errors"
"gopkg.in/olivere/elastic.v3"
2020-03-25 02:57:25 +00:00
"qiniupkg.com/x/log.v7"
)
2020-03-27 16:00:46 +00:00
const (
ERR_COLUMN_EXISTED = "column_existed"
)
func HardwareTypeMapping() (string){
return `"mappings":{
"hardware":{
"properties":{
"id":{"type":"keyword"},
"name":{"type":"keyword"},
"desc":{"type":"text"},
"pic":{"type":"doc"},
"doc":{"type":"doc"}
}
}
}`
}
// this api is based on elasticsearch
type Hardware struct {
2020-03-31 17:07:32 +00:00
ID string `json:"_id,omitempty"`
BuyDate string `json:"buy_date,omitempty"` //购入时间
Name string `json:"name,omitempty"` // 名字
Desc string `json:"desc,omitempty"` // 描述
Pic string `json:"pic,omitempty"` // 图片
Doc string `json:"doc,omitempty"` //文档资料
}
2020-03-25 02:57:25 +00:00
func (this *Hardware )CreateHardware( ) error{
if nil == this{
2020-03-27 16:00:46 +00:00
return errors.New(utils.ERRNULLPOINTER)
}
log.Print(this.Name)
matchPhraseQuery := elastic.NewMatchQuery("name", this.Name)
2020-03-31 17:07:32 +00:00
existedHardware,e := QueryHardwares(matchPhraseQuery,10,0)
log.Print(e,existedHardware)
2020-03-31 17:07:32 +00:00
for _,v := range existedHardware{
if v.Name == this.Name{
log.Print(v.ID)
return errors.New(ERR_COLUMN_EXISTED)
}
2020-03-25 02:57:25 +00:00
}
2020-03-27 16:00:46 +00:00
e = db.GetElastic().Create("hardware","0","",*this)
2020-03-25 02:57:25 +00:00
if nil != e{
log.Print("shit1")
2020-03-25 02:57:25 +00:00
log.Print(e.Error())
return e
}
log.Print("shit2")
return nil;
}
func GetHardwares(limit int,size int) ([]Hardware,error){
var ret []Hardware
2020-03-31 17:07:32 +00:00
data,ids,e := db.GetElastic().Query("hardware",nil,Hardware{},limit,size)
if nil != e{
return nil,e
}
2020-03-31 17:07:32 +00:00
i := 0
for _,v := range data{
ret = append(ret,v.(Hardware))
2020-03-31 17:07:32 +00:00
ret[i].ID = ids[i]
i++
}
return ret,nil
}
2020-03-26 12:15:04 +00:00
func QueryHardwares(query elastic.Query,limit int,offset int) ([]Hardware,error){
var ret []Hardware
2020-03-31 17:07:32 +00:00
data,ids,e := db.GetElastic().Query("hardware",query,Hardware{},limit,offset)
log.Print(data)
if nil != e{
return nil,e
}
2020-03-31 17:07:32 +00:00
i := 0
for _,v := range data{
ret = append(ret,v.(Hardware))
2020-03-31 17:07:32 +00:00
ret[i].ID = ids[i]
i++
}
return ret,nil
2020-03-31 17:07:32 +00:00
}
func DeleteHardware(name string) error{
matchPhraseQuery := elastic.NewMatchQuery("name", "stm32开发板")
existedHardware,e := QueryHardwares(matchPhraseQuery,10,0)
log.Print(e,existedHardware)
for _,v := range existedHardware{
if v.Name == name{
err := db.GetElastic().Delete("hardware","",v.ID)
if err != nil {
return err
}
}
}
return nil
}