MarketingSystemDataTool/server/internal/api/ymt_merchants.go

63 lines
1.7 KiB
Go

package api
import (
"database/sql"
"net/http"
"strconv"
)
type YMTMerchantsAPI struct {
ymt *sql.DB
}
func YMTMerchantsHandler(ymt *sql.DB) http.Handler {
api := &YMTMerchantsAPI{ymt: ymt}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodGet {
api.list(w, r)
return
}
w.WriteHeader(http.StatusNotFound)
})
}
func (a *YMTMerchantsAPI) list(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
userIDStr := q.Get("user_id")
like := q.Get("q")
limitStr := q.Get("limit")
limit := 2000
if limitStr != "" {
if n, err := strconv.Atoi(limitStr); err == nil && n > 0 && n <= 10000 { limit = n }
}
sql1 := "SELECT id, name FROM merchant WHERE id IS NOT NULL"
args := []interface{}{}
if userIDStr != "" {
sql1 += " AND user_id = ?"
args = append(args, userIDStr)
}
if like != "" {
sql1 += " AND (CAST(id AS CHAR) LIKE ? OR name LIKE ?)"
s := "%" + like + "%"
args = append(args, s, s)
}
sql1 += " ORDER BY id ASC LIMIT ?"
args = append(args, limit)
rows, err := a.ymt.Query(sql1, args...)
if err != nil {
fail(w, r, http.StatusInternalServerError, err.Error())
return
}
defer rows.Close()
out := []map[string]interface{}{}
for rows.Next() {
var id sql.NullInt64
var name sql.NullString
if err := rows.Scan(&id, &name); err != nil { continue }
if !id.Valid { continue }
out = append(out, map[string]interface{}{"id": id.Int64, "name": name.String})
}
ok(w, r, out)
}