courses/api_products.go

88 lines
2.3 KiB
Go

package main
import (
"encoding/json"
"errors"
"net/url"
"strconv"
)
var ApiProductsRouting = map[string]DispatchFunction{
"GET": listProduct,
"POST": addProduct,
"DELETE": delProduct,
"PATCH": editProduct,
}
func listProduct(args []string, body []byte) ([]byte, error) {
if len(args) < 1 {
if products, err := GetProducts(); err != nil {
return nil, err
} else if ret, err := json.Marshal(products); err != nil {
return nil, err
} else {
return ret, nil
}
} else if i, err := strconv.ParseInt(args[0], 10, 64); err != nil {
return nil, err
} else {
if product, err := GetProduct(i); err != nil {
return nil, err
} else if ret, err := json.Marshal(product); err != nil {
return nil, err
} else {
return ret, nil
}
}
}
func addProduct(args []string, body []byte) ([]byte, error) {
if m, err := url.ParseQuery(string(body)); err != nil {
return nil, err
} else if name := m.Get("name"); name == "" {
return nil, errors.New("No product name given")
} else if id, err := AddProduct(name); err != nil {
return nil, err
} else if r, err := json.Marshal(map[string]int64{"id": id}); err != nil {
return nil, err
} else {
return r, nil
}
}
func delProduct(args []string, body []byte) ([]byte, error) {
if len(args) < 1 {
return nil, errors.New("Need a product identifier to delete")
} else if id, err := strconv.ParseInt(args[0], 10, 64); err != nil {
return nil, err
} else if nb, err := RemoveProduct(id); err != nil {
return nil, err
} else if nb <= 0 {
return nil, errors.New("No matching product")
} else if r, err := json.Marshal(map[string]int64{"nb": nb}); err != nil {
return nil, err
} else {
return r, nil
}
}
func editProduct(args []string, body []byte) ([]byte, error) {
if len(args) < 1 {
return nil, errors.New("Need a product identifier to patch")
} else if id, err := strconv.ParseInt(args[0], 10, 64); err != nil {
return nil, err
} else if m, err := url.ParseQuery(string(body)); err != nil {
return nil, err
} else if name := m.Get("name"); name == "" {
return nil, errors.New("No product name given")
} else if nb, err := UpdateProduct(id, name); err != nil {
return nil, err
} else if nb <= 0 {
return nil, errors.New("No matching product")
} else if r, err := json.Marshal(map[string]int64{"nb": nb}); err != nil {
return nil, err
} else {
return r, nil
}
}