78 lines
1.7 KiB
Go
78 lines
1.7 KiB
Go
// package shopify calls the Shopify GraphQL Apu Endpoint
|
|
// This package rquires the follwing ENV vars to be set:
|
|
//
|
|
// SHOPIFY_GRAPHQL_ENDPOINT
|
|
// SHOPIFY_TOKEN
|
|
package shopify
|
|
|
|
import (
|
|
"bytes"
|
|
"io/ioutil"
|
|
"net/http"
|
|
"strconv"
|
|
"time"
|
|
"os"
|
|
|
|
"github.com/m3tam3re/errors"
|
|
"github.com/valyala/fastjson"
|
|
)
|
|
|
|
var endpoint = os.Getenv("SHOPIFY_GRAPHQL_ENDPOINT")
|
|
|
|
func StartRequest(body []byte) (*http.Response, error) {
|
|
path := ""
|
|
const op errors.Op = "func: startRequest"
|
|
|
|
client := http.Client{
|
|
Timeout: time.Second * 120,
|
|
}
|
|
req, err := http.NewRequest("POST", endpoint, bytes.NewBuffer(body))
|
|
if err != nil {
|
|
return nil, errors.E(errors.Internal, op, path, err, "error building request")
|
|
}
|
|
req.Header.Add("X-Shopify-Access-Token",os.Getenv("SHOPIFY_TOKEN"))
|
|
req.Header.Add("Content-Type", "application/graphql")
|
|
resp, err := client.Do(req)
|
|
if err != nil {
|
|
return nil, errors.E(errors.Internal, op, path, err, "error executing request")
|
|
}
|
|
return resp, nil
|
|
}
|
|
|
|
func GetItemPrice(sku string) (float32, error) {
|
|
qu := `{
|
|
inventoryItems(first:1, query:"sku:` + sku + `") {
|
|
edges{
|
|
node{
|
|
sku
|
|
variant {
|
|
price
|
|
compareAtPrice
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}`
|
|
resp, err := StartRequest([]byte(qu))
|
|
defer resp.Body.Close()
|
|
body, err := ioutil.ReadAll(resp.Body)
|
|
if err != nil {
|
|
//TODO handle error
|
|
}
|
|
p := fastjson.GetString(body, "data", "inventoryItems", "edges", "0", "node", "variant", "price")
|
|
cp := fastjson.GetString(body, "data", "inventoryItems", "edges", "0", "node", "variant", "compareAtPrice")
|
|
|
|
var finalPrice string
|
|
if cp != "" {
|
|
finalPrice = cp
|
|
} else {
|
|
finalPrice = p
|
|
}
|
|
|
|
price, err:= strconv.ParseFloat(finalPrice, 32)
|
|
if err != nil {
|
|
//TODO handle error
|
|
}
|
|
return float32(price), nil
|
|
}
|