Beispiel #1
0
func storesHandler(api *apidb.Api) func(w http.ResponseWriter, r *http.Request) {
	return func(w http.ResponseWriter, r *http.Request) {
		setHeaders(w, r)
		js, err := json.Marshal(api.GetAllStores())
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		w.Header().Set("Content-Type", "application/json")
		w.Write(js)
	}
}
Beispiel #2
0
func purchasesHandler(api *apidb.Api) func(w http.ResponseWriter, r *http.Request) {
	return func(w http.ResponseWriter, r *http.Request) {
		setHeaders(w, r)
		vars := mux.Vars(r)
		productId, err := strconv.ParseInt(vars["productId"], 10, 64)
		storeId, err := strconv.ParseInt(vars["storeId"], 10, 64)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		stores := api.GetAllStores()
		var foundStore apidb.Store
		for _, store := range stores {
			if store.Id == storeId {
				foundStore = store
				break
			}
		}

		products := api.GetAllProducts()
		var foundProduct apidb.Product
		for _, product := range products {
			if product.Id == productId {
				foundProduct = product
				break
			}
		}

		if foundStore.Id != storeId || foundProduct.Id != productId {
			http.Error(w, "cannot find store or product", http.StatusInternalServerError)
			return
		}

		receipts := api.GetAllReceipts()
		var foundReceipts []apidb.Receipt = make([]apidb.Receipt, 0)
		for _, receipt := range receipts {
			if receipt.Store_id == foundStore.Id {
				foundReceipts = append(foundReceipts, receipt)
			}
		}

		purchases := api.GetAllPurchases()
		var foundPurchases []apidb.Purchase = make([]apidb.Purchase, 0)
		for _, purchase := range purchases {
			if purchase.Product_id == foundProduct.Id {
				for _, receipt := range foundReceipts {
					if purchase.Receipt_id == receipt.Id {
						foundPurchases = append(foundPurchases, purchase)
						break
					}
				}
			}
		}

		w.Header().Set("Content-Type", "application/json")
		js, err := json.Marshal(foundPurchases)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		w.Write(js)
	}
}