replaycli-go/api/dataapi/lib.go

108 lines
2.1 KiB
Go

package dataapi
import (
"strconv"
"time"
"go.digitalcircle.com.br/open/httpcli"
)
type DataApiOp string
const (
RETRIEVE DataApiOp = "R"
CREATE DataApiOp = "C"
DELETE DataApiOp = "D"
UPDATE DataApiOp = "U"
)
type DataAPIRequest struct {
Col string `json:"col"`
Q string `json:"q"`
Op DataApiOp `json:"op"`
Id string `json:"id"`
Data map[string]interface{} `json:"data"`
}
type DataAPIResponse struct {
Msg string `json:"msg"`
Id string `json:"id"`
Data []interface{} `json:"data"`
}
type Cli struct {
Httpcli *httpcli.Cli
}
func (c *Cli) Do(request *DataAPIRequest) (response *DataAPIResponse, err error) {
response = &DataAPIResponse{}
err = c.Httpcli.JsonPost("/", request, response)
return
}
func NewCli(apikey string) *Cli {
ret := &Cli{Httpcli: httpcli.NewCli()}
ret.Httpcli.AddHeader("X-API-KEY", apikey)
ret.Httpcli.SetBasePath("https://dataapi.digitalcircle.com.br")
return ret
}
func LCR_Create() {
c := NewCli("RnJpIDA1IE5vdiAyMDIxIDExOjE1OjIyIEFNIFVUQwo")
_, err := c.Do(&DataAPIRequest{
Col: "LCR_Bot",
Op: CREATE,
Data: map[string]interface{}{
"Registro": "1",
},
})
if err != nil {
panic(err)
}
}
func RegistrarExec(table string) {
//Para robôs, age como contador e registra cada repetição no mês
c := NewCli("RnJpIDA1IE5vdiAyMDIxIDExOjE1OjIyIEFNIFVUQwo")
current := time.Now().Format("2006-01")
res, err := c.Do(&DataAPIRequest{
Col: table,
Op: RETRIEVE,
Q: "@[?date=='" + current + "']",
})
if err != nil {
panic(err)
}
if len(res.Data) > 0 {
result := res.Data[0].(map[string]interface{})
registros := result["exec"].(float64)
registros = registros + 1
ident := strconv.Itoa(int(result["ID"].(float64)))
_, err = c.Do(&DataAPIRequest{
Col: table,
Op: UPDATE,
Id: ident,
Data: map[string]interface{}{
"exec": registros,
},
})
if err != nil {
panic(err)
}
} else {
_, err = c.Do(&DataAPIRequest{
Col: table,
Op: CREATE,
Data: map[string]interface{}{
"date": current,
"exec": 1,
},
})
if err != nil {
panic(err)
}
}
}