ess-etl-go/internal/request/request.go

88 lines
2.1 KiB
Go
Raw Normal View History

package request
import (
"fmt"
"io"
"net/http"
"strings"
)
type RequestService struct {
api string
apiKey string
}
func NewRequestService(api, apiKey string) RequestService {
return RequestService{
api: api,
apiKey: apiKey,
}
}
func getPayload(employeeIDList []string) (string, error) {
employees := strings.Builder{}
_, err := employees.Write([]byte(`<EmployeeWorkInformationQuery xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><EmployeeNumbers>`))
if err != nil {
return "", fmt.Errorf("error while write headers: %s", err)
}
for _, employeeID := range employeeIDList {
employees.Write([]byte("<string>" + employeeID + "</string>"))
}
_, err = employees.Write([]byte("</EmployeeNumbers></EmployeeWorkInformationQuery>"))
if err != nil {
return "", fmt.Errorf("error while write footer: %s", err)
}
return employees.String(), nil
}
func (r RequestService) EmployeeWorkInformation(data *[]byte, employeeIDList []string, from, to string) error {
url := r.api + "/EmployeeWorkInformation/Search/" + from + "/" + to + "/"
stringPayload, err := getPayload(employeeIDList)
if err != nil {
return fmt.Errorf("getPayload: %s", err)
}
payload := strings.NewReader(stringPayload)
client := &http.Client{}
req, err := http.NewRequest("POST", url, payload)
if err != nil {
return fmt.Errorf("http.NewRequest: %s", err)
}
req.Header.Add("Cache-Control", "no-cache")
req.Header.Add("Authorization", r.apiKey)
req.Header.Add("Content-Type", "application/xml")
res, err := client.Do(req)
if err != nil {
return fmt.Errorf("client.Do: %s", err)
}
defer res.Body.Close()
for {
if len(*data) == cap(*data) {
// Add more capacity (let append pick how much).
*data = append(*data, 0)[:len(*data)]
}
n, err := res.Body.Read((*data)[len(*data):cap(*data)])
*data = (*data)[:len(*data)+n]
if err != nil {
if err == io.EOF {
err = nil
}
return err
}
}
// data, err = io.ReadAll(res.Body)
// if err != nil {
// return fmt.Errorf("ioutil.ReadAll: %s", err)
// }
//log.Println("readed", string(body))
return nil
}