Skip to content

Commit

Permalink
added connection from bungalow availability check (javascript) to /re…
Browse files Browse the repository at this point in the history
…servation-json handler (generating JSON response)
  • Loading branch information
jagottsicher committed Jul 10, 2023
1 parent dc78d17 commit dc3a913
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 8 deletions.
49 changes: 46 additions & 3 deletions internal/handlers/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -128,15 +128,58 @@ type jsonResponse struct {

// ReservationJSON is the handler for reservation-json and returns JSON
func (m *Repository) ReservationJSON(w http.ResponseWriter, r *http.Request) {

bungalowID, err := strconv.Atoi(r.Form.Get("bungalow_id"))
if err != nil {
helpers.ServerError(w, err)
return
}

sd := r.Form.Get("start")
ed := r.Form.Get("end")

layout := "2006-01-02"

startDate, err := time.Parse(layout, sd)
if err != nil {
helpers.ServerError(w, err)
return
}

endDate, err := time.Parse(layout, ed)
if err != nil {
helpers.ServerError(w, err)
return
}

available, err := m.DB.SearchAvailabilityByDatesByBungalowID(startDate, endDate, bungalowID)
if err != nil {
helpers.ServerError(w, err)
resp := jsonResponse{
OK: false,
Message: "Error querying database",
}

output, err := json.MarshalIndent(resp, "", " ")
if err != nil {
helpers.ServerError(w, err)
return
}

w.Header().Set("Content-Type", "application/json")
w.Write(output)

return
}

resp := jsonResponse{
OK: false,
Message: "It's available!",
OK: available,
Message: "",
}

output, err := json.MarshalIndent(resp, "", " ")
if err != nil {
helpers.ServerError(w, err)
return
}

w.Header().Set("Content-Type", "application/json")
Expand Down
4 changes: 2 additions & 2 deletions internal/repository/dbrepo/postgres.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,11 +85,11 @@ func (m *postgresDBRepo) SearchAvailabilityByDatesByBungalowID(start, end time.T
query := `
select
count(id)
fromw
from
bungalow_restrictions
where
bungalow_id = $1
$2 <= end_date and $3 >= start_date;
and $2 <= end_date and $3 >= start_date;
`

row := m.DB.QueryRowContext(ctx, query, bungalowID, start, end)
Expand Down
9 changes: 6 additions & 3 deletions templates/eremite-page.tpml
Original file line number Diff line number Diff line change
Expand Up @@ -79,16 +79,19 @@
let form = document.getElementById("check-availability-form");
let = formData = new FormData(form);
formData.append("csrf_token", "{{.CSRFToken}}");
formData.append("bungalow_id", "1")

fetch('/reservation-json', {
method: "POST",
body: formData,
})
.then(response => response.json())
.then (data => {
console.log(data)
console.log(data.ok)
console.log(data.message)
if (data.ok) {
console.log("Available.")
} else {
console.log("NOT Available.")
}
})
}
});
Expand Down

0 comments on commit dc3a913

Please sign in to comment.