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 #85, #58 #86

Merged
merged 2 commits into from
Nov 20, 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
2 changes: 1 addition & 1 deletion backend/cmd/dbcli/cli_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ func TestCli(t *testing.T) {
Description: ptr("Bla bla"),
StartTimeUtc: ptr(time.Date(2024, 5, 7, 1, 1, 1, 1, time.UTC)),
DurationMinutes: ptr(int16(30)),
Interval: ptr("Weekly"),
Interval: ptr(types.Weekly),
}
testSessionJson, err := json.Marshal(testSessionProps)
if err != nil {
Expand Down
110 changes: 18 additions & 92 deletions backend/cmd/server/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,94 +19,6 @@ import (
"github.com/jackc/pgx/v5/pgtype"
)

type Interval int

const (
Once Interval = iota
Daily
Weekly
Fortnightly
FirstOfMonth
SecondOfMonth
ThirdOfMonth
FourthOfMonth
LastOfMonth
IrregularWeekly
)

type Backline int

const (
PA Backline = iota
GuitarAmp
BassAmp
Drums
Keys
Mic
MiscPercussion
)

var backlineStrToEnum = map[string]Backline{
"PA": PA,
"Guitar_Amp": GuitarAmp,
"Bass_Amp": BassAmp,
"Drums": Drums,
"Microphone": Mic,
"MiscPercussion": MiscPercussion,
"Keys": Keys,
}

func (b Backline) String() string {
for k, v := range backlineStrToEnum {
if v == b {
return k
}
}
return ""
}

type Genre int

const (
Any Genre = iota
StraightAhead
JazzFunk
Fusion
LatinJazz
ModernJazz
TradJazz
Funk
Blues
Folk
Rock
Pop
WorldMusic
)

var genreStrToEnum = map[string]Genre{
"Straight-Ahead_Jazz": StraightAhead,
"Jazz-Funk": JazzFunk,
"Fusion": Fusion,
"Latin_Jazz": LatinJazz,
"Funk": Funk,
"Blues": Blues,
"Folk": Folk,
"Rock": Rock,
"Pop": Pop,
"World_Music": WorldMusic,
"Modern_Jazz": ModernJazz,
"Trad_Jazz": TradJazz,
}

func (b Genre) String() string {
for k, v := range genreStrToEnum {
if v == b {
return k
}
}
return ""
}

func GetVenues(c *fuego.ContextNoBody) (types.VenueFeatureCollection, error) {
var geojson types.FeatureCollection[types.VenueFeature]
result, err := queries.GetAllVenuesAsGeoJSON(ctx)
Expand Down Expand Up @@ -156,17 +68,17 @@ func GetSessions(c *fuego.ContextNoBody) (types.SessionWithVenueFeatureCollectio
} else if k == "backline" {
backlineSlice := strings.Split(c.QueryParam("backline"), ",")
for _, b := range backlineSlice {
_, ok := backlineStrToEnum[b]
_, ok := types.BacklineOptions[types.Backline(b)]
if !ok {
return geojson, fuego.BadRequestError{Detail: fmt.Sprintf("%v is not a valid value for 'backline'", b)}
}
}
backline = &backlineSlice
} else if k == "genre" {
genreParam := c.QueryParam("genre")
_, ok := genreStrToEnum[genreParam]
_, ok := types.Genres[types.Genre(genreParam)]
if !ok {
return geojson, fuego.BadRequestError{Detail: fmt.Sprintf("%v is not a valid value for 'genre'", genre)}
return geojson, fuego.BadRequestError{Detail: fmt.Sprintf("%v is not a valid value for 'genre'", genreParam)}
}
genre = &genreParam
} else {
Expand Down Expand Up @@ -248,7 +160,9 @@ func GetSessions(c *fuego.ContextNoBody) (types.SessionWithVenueFeatureCollectio
if err != nil {
return geojson, err
}
json.Unmarshal(result, &geojson)
if err := json.Unmarshal(result, &geojson); err != nil {
return geojson, err
}
slog.Info("GetSessions", "result", geojson)
return geojson, nil
}
Expand Down Expand Up @@ -302,6 +216,9 @@ func PostSession(c *fuego.ContextWithBody[types.SessionPropertiesWithVenue]) (ty
slog.Info("PostSession", "payload", payload)
if err != nil {
slog.Error("PostSession", "msg", err)
if errors.As(err, &types.ValidationError{}) {
return types.SessionFeature[types.SessionProperties]{}, fuego.BadRequestError{Detail: err.Error()}
}
return types.SessionFeature[types.SessionProperties]{}, errors.New("an unknown error occured")
}
var cmd string
Expand Down Expand Up @@ -352,6 +269,9 @@ func PatchSessionById(c *fuego.ContextWithBody[types.SessionProperties]) (types.
}
payload, err := c.Body()
if err != nil {
if errors.As(err, &types.ValidationError{}) {
return types.SessionFeature[types.SessionProperties]{}, fuego.BadRequestError{Detail: err.Error()}
}
slog.Error("PatchSessionById", "id", id, "msg", err)
return types.SessionFeature[types.SessionProperties]{}, errors.New("an unknown error occured")
}
Expand Down Expand Up @@ -477,6 +397,9 @@ func PostVenue(c *fuego.ContextWithBody[types.VenueProperties]) (types.VenueFeat
payload, err := c.Body()
if err != nil {
slog.Error("PostVenue", "msg", err)
if errors.As(err, &types.ValidationError{}) {
return types.VenueFeature{}, fuego.BadRequestError{Detail: err.Error()}
}
return types.VenueFeature{}, errors.New("an unknown error occured")
}
j, err := json.Marshal(payload)
Expand Down Expand Up @@ -504,6 +427,9 @@ func PatchVenueById(c *fuego.ContextWithBody[types.VenueProperties]) (types.Venu
payload, err := c.Body()
if err != nil {
slog.Error("PatchVenueById", "id", id, "msg", err)
if errors.As(err, &types.ValidationError{}) {
return types.VenueFeature{}, fuego.BadRequestError{Detail: err.Error()}
}
return types.VenueFeature{}, errors.New("an unknown error occured")
}
j, err := json.Marshal(payload)
Expand Down
68 changes: 65 additions & 3 deletions backend/cmd/server/handlers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -281,6 +281,68 @@ func TestHandlers(t *testing.T) {
checkResultSetForSessionIds(t, []int32{testSession1Id, testSession2Id}, body)
})

t.Run("GetSessionsByWrongGenre", func(t *testing.T) {
handler := fuego.HTTPHandler(s, GetSessions)
req := httptest.NewRequest(http.MethodGet, "/jamsessions?genre=Foobar", nil)
w := httptest.NewRecorder()
handler(w, req)
res := w.Result()
defer res.Body.Close()
if res.StatusCode != 400 {
t.Error("expected a 400 status, got", res.StatusCode)
}
data, err := io.ReadAll(res.Body)
if err != nil {
t.Errorf("expected error to be nil got %v", err)
}
if !strings.Contains(string(data), "Foobar") {
t.Errorf("expected the body (%s) to contain the string Foobar", data)
}
})

t.Run("PatchSession", func(t *testing.T) {
// temp directory for migrations
migrationsDirectory = t.TempDir()

handler := fuego.HTTPHandler(s, PatchSessionById)
req := httptest.NewRequest(http.MethodPatch, fmt.Sprintf("/jamsessions/%v", testSession2Id), strings.NewReader(`{"interval": "Once"}`))
req.SetPathValue("id", fmt.Sprint(testSession2Id))
w := httptest.NewRecorder()
handler(w, req)
res := w.Result()
defer res.Body.Close()
if res.StatusCode != 200 {
t.Error("expected a 200 status, got", res.StatusCode)
}
_, err := io.ReadAll(res.Body)
if err != nil {
t.Errorf("expected error to be nil got %v", err)
}
})

t.Run("PatchSessionError", func(t *testing.T) {
// temp directory for migrations
migrationsDirectory = t.TempDir()

handler := fuego.HTTPHandler(s, PatchSessionById)
req := httptest.NewRequest(http.MethodPatch, fmt.Sprintf("/jamsessions/%v", testSession1Id), strings.NewReader(`{"interval": "Never"}`))
req.SetPathValue("id", fmt.Sprint(testSession1Id))
w := httptest.NewRecorder()
handler(w, req)
res := w.Result()
defer res.Body.Close()
if res.StatusCode != 400 {
t.Error("expected a 400 status, got", res.StatusCode)
}
data, err := io.ReadAll(res.Body)
if err != nil {
t.Errorf("expected error to be nil got %v", err)
}
if !strings.Contains(string(data), "Never") {
t.Errorf("expected the body (%s) to contain the string Foobar", data)
}
})

//test currently failing - not essential, but should be looked into at some point
// t.Run("GetSessionsByDateAndBacklineNoMatch", func(t *testing.T) {
// handler := fuego.HTTPHandler(s, GetSessions)
Expand Down Expand Up @@ -456,7 +518,7 @@ func TestHandlers(t *testing.T) {
Description: ptr("Description."),
StartTimeUtc: ptr(time.Date(2024, 3, 4, 5, 5, 3, 5, time.UTC)),
DurationMinutes: ptr(int16(90)),
Interval: ptr("FirstOfMonth"),
Interval: ptr(types.FirstOfMonth),
SessionWebsite: ptr("https://example.org"),
})
if err != nil {
Expand Down Expand Up @@ -507,7 +569,7 @@ func TestHandlers(t *testing.T) {
Description: ptr("Description."),
StartTimeUtc: ptr(time.Date(2024, 3, 4, 5, 5, 3, 5, time.UTC)),
DurationMinutes: ptr(int16(90)),
Interval: ptr("FirstOfMonth"),
Interval: ptr(types.FirstOfMonth),
SessionWebsite: ptr("https://example.org"),
},
VenueProperties: types.VenueProperties{
Expand All @@ -516,7 +578,7 @@ func TestHandlers(t *testing.T) {
City: ptr("Randomtown"),
Postcode: ptr("ABC 123"),
VenueWebsite: ptr("https://example.org"),
Backline: &[]string{"PA", "Drums"},
Backline: &[]types.Backline{types.PA, types.Drums},
},
})
if err != nil {
Expand Down
2 changes: 1 addition & 1 deletion backend/internal/db/schema.sql
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ CREATE TABLE london_jam_sessions.jamsessions (
session_id SERIAL PRIMARY KEY,
session_name VARCHAR(250) NOT NULL,
venue INTEGER NOT NULL REFERENCES london_jam_sessions.venues(venue_id) ON DELETE CASCADE, -- if a venue is deleted, all sessions associated with the venue should be deleted too
genres VARCHAR(50)[] CHECK(genres <@ ARRAY['Straight-Ahead_Jazz'::VARCHAR, 'Modern_Jazz'::VARCHAR, 'Trad_Jazz'::VARCHAR, 'Jazz-Funk'::VARCHAR, 'Fusion'::VARCHAR, 'Latin_Jazz'::VARCHAR, 'Funk'::VARCHAR, 'Blues'::VARCHAR, 'Folk'::VARCHAR, 'Rock'::VARCHAR, 'Pop'::VARCHAR, 'World_Music'::VARCHAR]),
genres VARCHAR(50)[] CHECK(genres <@ ARRAY['Straight-Ahead_Jazz'::VARCHAR, 'Modern_Jazz'::VARCHAR, 'Trad_Jazz'::VARCHAR, 'Jazz-Funk'::VARCHAR, 'Fusion'::VARCHAR, 'Latin_Jazz'::VARCHAR, 'Funk'::VARCHAR, 'RnB'::VARCHAR, 'Hip-Hop'::VARCHAR, 'Blues'::VARCHAR, 'Folk'::VARCHAR, 'Rock'::VARCHAR, 'Pop'::VARCHAR, 'World_Music'::VARCHAR]),
start_time_utc TIMESTAMPTZ NOT NULL,
interval VARCHAR(50) NOT NULL CHECK (interval IN ('Once', 'Daily', 'Weekly', 'Fortnightly', 'FirstOfMonth', 'SecondOfMonth', 'ThirdOfMonth', 'FourthOfMonth', 'LastOfMonth', 'IrregularWeekly')),
duration_minutes SMALLINT NOT NULL,
Expand Down
Loading