Creating Filters struct and using it inside our listMoviesHandler

This commit is contained in:
Maxime Delporte
2025-11-11 10:47:25 +01:00
parent 041d302a79
commit bf7c53e565
2 changed files with 13 additions and 8 deletions

View File

@@ -206,11 +206,9 @@ func (app *application) deleteMovieHandler(w http.ResponseWriter, r *http.Reques
func (app *application) listMoviesHandler(w http.ResponseWriter, r *http.Request) { func (app *application) listMoviesHandler(w http.ResponseWriter, r *http.Request) {
// To keep things consistent with our other handlers, we'll define an input struct to hold the expected values from the request query string // To keep things consistent with our other handlers, we'll define an input struct to hold the expected values from the request query string
var input struct { var input struct {
Title string Title string
Genres []string Genres []string
Page int data.Filters
PageSize int
Sort string
} }
// Initialize a new Validator instance // Initialize a new Validator instance
@@ -224,11 +222,11 @@ func (app *application) listMoviesHandler(w http.ResponseWriter, r *http.Request
input.Genres = app.readCSV(qs, "genres", []string{}) input.Genres = app.readCSV(qs, "genres", []string{})
// Get the page and page_size query string values as integers. Notice that we set the default page value to 1 and default page_size to 20, and that we pass the validator instance as the final argument here // Get the page and page_size query string values as integers. Notice that we set the default page value to 1 and default page_size to 20, and that we pass the validator instance as the final argument here
input.Page = app.readInt(qs, "page", 1, v) input.Filters.Page = app.readInt(qs, "page", 1, v)
input.PageSize = app.readInt(qs, "page_size", 20, v) input.Filters.PageSize = app.readInt(qs, "page_size", 20, v)
// Extract the sort query string value, falling back to "id" if it is not provided by the client (which will imply an ascending sort on movie ID) // Extract the sort query string value, falling back to "id" if it is not provided by the client (which will imply an ascending sort on movie ID)
input.Sort = app.readString(qs, "sort", "id") input.Filters.Sort = app.readString(qs, "sort", "id")
// Check the Validator instance for any errors and use the failedValidationResponse() helper to send the client a response if necessary // Check the Validator instance for any errors and use the failedValidationResponse() helper to send the client a response if necessary
if !v.Valid() { if !v.Valid() {

7
internal/data/filters.go Normal file
View File

@@ -0,0 +1,7 @@
package data
type Filters struct {
Page int
PageSize int
Sort string
}