badge endpoint
This commit is contained in:
1 parent
ba60e22404
commit
9f0d7dc7d8
2 files changed
+145
No files matched your search
@@ -0,0 +1,51 @@
|
||||
package inventory
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// StockReader abstracts the inventory getter for badge rendering.
|
||||
type StockReader interface {
|
||||
GetInventory(ctx context.Context, sku SKU, locationID LocationID) (int64, error)
|
||||
}
|
||||
|
||||
// BadgeHandler returns an http.HandlerFunc that renders an HTML stock badge fragment.
|
||||
func BadgeHandler(reader StockReader) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
sku := r.URL.Query().Get("sku")
|
||||
if sku == "" {
|
||||
http.Error(w, "missing sku parameter", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
locationID := LocationID(r.URL.Query().Get("location_id"))
|
||||
if locationID == "" {
|
||||
locationID = "default"
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
w.Header().Set("Cache-Control", "private, max-age=5")
|
||||
|
||||
qty, err := reader.GetInventory(r.Context(), SKU(sku), locationID)
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write([]byte(`<span class="stock-badge stock-unknown" data-sku="` + sku + `">Availability unavailable</span>`))
|
||||
return
|
||||
}
|
||||
|
||||
var htmlSnippet string
|
||||
switch {
|
||||
case qty > 10:
|
||||
htmlSnippet = fmt.Sprintf(`<span class="stock-badge stock-in-stock" data-sku="%s">✓ In stock</span>`, sku)
|
||||
case qty > 0:
|
||||
htmlSnippet = fmt.Sprintf(`<span class="stock-badge stock-low-stock" data-sku="%s">⚡ Only %d left!</span>`, sku, qty)
|
||||
default:
|
||||
htmlSnippet = fmt.Sprintf(`<span class="stock-badge stock-out-of-stock" data-sku="%s">✕ Out of stock</span>`, sku)
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write([]byte(htmlSnippet))
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user