Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

close #92, #93 #94

Merged
merged 2 commits into from
Nov 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions backend/cmd/server/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,26 @@ func GetVenueById(c *fuego.ContextNoBody) (types.VenueFeature, error) {
return geojson, nil
}

func GetSessionsByVenueId(c *fuego.ContextNoBody) (types.SessionWithVenueFeatureCollection, error) {
slog.Info("GetSessionsByVenueId", "id", c.PathParam("id"))
id, err := strconv.Atoi(c.PathParam("id"))
if err != nil {
return types.SessionWithVenueFeatureCollection{}, fuego.BadRequestError{Detail: fmt.Sprintf("Please provide a numeric ID ('/venues/{id}'), got: %v", c.PathParam("id"))}
}
result, err := queries.GetSessionsByVenueIdAsGeoJSON(ctx, int32(id))
if err != nil {
slog.Error("GetSessionsByVenueId", "msg", err)
return types.SessionWithVenueFeatureCollection{}, errors.New("an unknown error occured")
}
var geojson types.SessionWithVenueFeatureCollection
err = json.Unmarshal(result, &geojson)
if err != nil {
return geojson, err
}
slog.Info("GetVenueById", "result", geojson)
return geojson, nil
}

// the following handlers don't directly apply changes but rather prepare commits for the admin to manually run (make migrations or scripts/run-migrations.sh)
// this is to prevent users from directly modifying the database

Expand Down
60 changes: 59 additions & 1 deletion backend/cmd/server/handlers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,33 @@ func TestHandlers(t *testing.T) {
t.Errorf("the following error occured when trying to insert test session 2: %v", err)
}

testVenueId2, err := queries.InsertVenue(ctx, dbutils.InsertVenueParams{
VenueName: "TEST HANDLERS 2",
AddressFirstLine: "2 Main Street",
City: "London",
Postcode: "ABC 123",
Geom: geom.NewPoint(geom.XY).MustSetCoords([]float64{-0.502, 51.514}),
VenueWebsite: ptr("https://www.test.com/"),
Backline: []string{"PA", "Drums"},
VenueComments: []string{"Comment 1", "comment 2"},
})
if err != nil {
t.Errorf("the following error occurred when trying to insert a Venue record: %v", err)
}

// add test data - session (tests use ephemeral databases so no need for cleanup after tests)
testSession3Id, err := queries.InsertJamSession(ctx, dbutils.InsertJamSessionParams{
SessionName: "test_session3",
StartTimeUtc: pgtype.Timestamptz{Time: time.Date(2024, 1, 1, 19, 30, 0, 0, time.UTC), Valid: true},
Interval: "Weekly",
DurationMinutes: 120,
Venue: testVenueId2,
Genres: []string{"Blues", "Jazz-Funk"},
})
if err != nil {
t.Errorf("the following error occured when trying to insert test session 1: %v", err)
}

t.Run("GetAllVenues", func(t *testing.T) {
handler := fuego.HTTPHandler(s, GetVenues)
req := httptest.NewRequest(http.MethodGet, "/venues", nil)
Expand All @@ -126,9 +153,40 @@ func TestHandlers(t *testing.T) {
}
})

t.Run("GetSessionsByVenueId", func(t *testing.T) {
handler := fuego.HTTPHandler(s, GetSessionsByVenueId)
req := httptest.NewRequest(http.MethodGet, fmt.Sprintf("/venues/%v/jamsessions", testVenueId2), nil)
req.SetPathValue("id", fmt.Sprint(testVenueId2))
w := httptest.NewRecorder()
handler(w, req)
res := w.Result()
defer res.Body.Close()
data, err := io.ReadAll(res.Body)
if err != nil {
t.Errorf("expected error to be nil got %v", err)
}
var body types.SessionFeatureCollection
err = json.Unmarshal(data, &body)
if err != nil {
t.Errorf("expected error to be nil got %v", err)
}
if len(body.Features) != 1 {
var sessionNames []string = make([]string, len(body.Features))
var venues []int32 = make([]int32, len(body.Features))
for i, s := range body.Features {
sessionNames[i] = *s.Properties.SessionName
venues[i] = *s.Properties.Venue
}
t.Errorf("expected exactly 1 feature in the session feature collection, got sessions %v (with venues %v)", sessionNames, venues)
t.FailNow()
}

checkResultSetForSessionIds(t, []int32{testSession3Id}, body)
})

t.Run("GetAllSessions", func(t *testing.T) {
handler := fuego.HTTPHandler(s, GetSessions)
req := httptest.NewRequest(http.MethodGet, "/sessions", nil)
req := httptest.NewRequest(http.MethodGet, "/jamsessions", nil)
w := httptest.NewRecorder()
handler(w, req)
res := w.Result()
Expand Down
4 changes: 3 additions & 1 deletion backend/cmd/server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,9 @@ func main() {

fuego.Get(v1, "/venues", GetVenues).Summary("Get all venues")

fuego.Get(v1, "/venues/{id}", GetVenueById).Summary("Get a venues by its ID")
fuego.Get(v1, "/venues/{id}", GetVenueById).Summary("Get a venue by its ID")

fuego.Get(v1, "/venues/{id}/jamsessions", GetSessionsByVenueId).Summary("Get jam sessions by venue ID")

fuego.Post(v1, "/venues", PostVenue).Summary("Add a venue")

Expand Down
2 changes: 1 addition & 1 deletion backend/doc/openapi.json

Large diffs are not rendered by default.

13 changes: 13 additions & 0 deletions backend/internal/db/query.sql
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,19 @@ SELECT public.ST_AsGeoJSON(t.*) FROM t;
SELECT * FROM london_jam_sessions.venues
WHERE venue_name = $1;

-- name: GetSessionsByVenueIdAsGeoJSON :one
WITH t AS (
SELECT s.*, l.*, coalesce(round(avg(rating), 2), 0)::real AS rating FROM london_jam_sessions.jamsessions s
JOIN london_jam_sessions.venues l ON s.venue = l.venue_id
LEFT OUTER JOIN london_jam_sessions.ratings r ON s.session_id = r.session
WHERE l.venue_id = $1
GROUP BY s.session_id, l.venue_id
)
SELECT json_build_object(
'type', 'FeatureCollection',
'features', json_agg(public.ST_AsGeoJSON(t.*)::json)
) FROM t;

-- name: GetCommentsBySessionId :many
SELECT c.*, r.rating, r.rating_id FROM london_jam_sessions.comments c
LEFT OUTER JOIN london_jam_sessions.ratings r ON c.comment_id = r.comment
Expand Down
21 changes: 21 additions & 0 deletions backend/internal/db/query.sql.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

42 changes: 30 additions & 12 deletions frontend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
"@sveltejs/vite-plugin-svelte": "^4.0.0",
"@types/eslint": "^9.6.0",
"@types/geojson": "^7946.0.14",
"@types/node": "^22.10.1",
"eslint": "^9.0.0",
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-svelte": "^2.45.1",
Expand Down
13 changes: 11 additions & 2 deletions frontend/src/api.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Backline, Genre, type CommentBody, type SessionWithVenueFeatureCollection, type SessionComment, type VenuesFeatureCollection, type SessionWithVenueFeature, type VenueFeature, type VenueProperties, type SessionProperties, type SessionPropertiesWithVenue } from "./types";
import { Backline, Genre, type CommentBody, type SessionWithVenueFeatureCollection, type SessionComment, type VenuesFeatureCollection, type SessionWithVenueFeature, type VenueFeature, type VenueProperties, type SessionProperties, type SessionPropertiesWithVenue, type SessionFeatureCollection } from "./types";

const API_ROOT = process.env.API_ADDRESS.replace("/\/$/", "");
const API_ROOT = process.env.API_ADDRESS?.replace("/\/$/", "");
const API_VERSION = "v1";

const API_ADDRESS = API_ROOT + "/" + API_VERSION;
Expand Down Expand Up @@ -63,6 +63,15 @@ export const getSessionById = async (id: number): Promise<SessionWithVenueFeatur
}
}

export const getSessionsByVenueId = async (venueId: number): Promise<SessionWithVenueFeatureCollection> => {
let response = await fetch(API_ADDRESS + "/venues/" + venueId + "/jamsessions")
if (!response.ok) {
throw new Error((await response.json() as ErrorResponse)["detail"])
} else {
return await response.json() as SessionWithVenueFeatureCollection;
}
}

export const getVenueById = async (id: number): Promise<VenueFeature> => {
let response = await fetch(API_ADDRESS + "/venues/" + id)
if (!response.ok) {
Expand Down
11 changes: 2 additions & 9 deletions frontend/src/lib/FilterMenu.svelte
Original file line number Diff line number Diff line change
@@ -1,13 +1,7 @@
<script lang="ts">
import {
loading,
filterMenuVisible,
selectedSessions,
visibleLayer,
selectedDateRange
} from '../stores';
import { loading, filterMenuVisible, selectedSessions, selectedDateRange } from '../stores';
import Modal from './Modal.svelte';
import { Backline, Genre, type SessionFeatureCollection, MapLayer } from '../types';
import { Backline, Genre, type SessionFeatureCollection } from '../types';
import { getSessions, type SessionOptions } from '../api';
import MultiSelect from './MultiSelect.svelte';
import MicrophoneIcon from './icons/MicrophoneIcon.svelte';
Expand Down Expand Up @@ -56,7 +50,6 @@
alert('An error occured when waiting for data from the server: ' + (e as Error).message);
throw e;
}
$visibleLayer = MapLayer.SESSIONS;
$loading = false;
};

Expand Down
Loading