In this lesson, you gave the problem list’s query string a Zod schema, so a limit that isn’t a number gets an error instead of an empty list.
Key Points
- Everything in a URL arrives as text. Express hands you a single query value or a route parameter as a string. A repeated key, as in
?limit=5&limit=6, gives an array:["5", "6"]. In/problems/2?limit=5, the id is"2"and the limit is"5", and"2" === 2isfalse. - An unchecked limit fails quietly. Before this lesson,
GET /problems?limit=abcanswered200 OKwith[]. The handler turned the limit into a number withNumber(), which gaveNaN, and.slice()treatsNaNas0. z.number()refuses a string, even"5".z.coerce.number()runsNumber()on the value first and then checks the result, so"5"comes out as the number5.- Coerce only what means a number. The grade and colour filters stay strings. They take their fields from
Problemthrough its.shapeproperty, which holds each field’s schema, and add.optional(). The wall’s ids are strings too, so the id’s schema is a plainz.string(). The limit is coerced and must be a whole number of at least 1 (.int().min(1)). When the client leaves it out, it defaults to20, so a list without a limit now stops at 20 problems. - Each limit takes its own path through the schema.
"5"becomes5and passes."abc"becomesNaNand fails the number check. No limit at all skips coercion, and the default makes it20. An empty limit,?limit=, fails.min(1). - Watch out for the empty string.
Number("")is0, notNaN, so an empty limit passes the number check and only.min(1)stops it. With.min(0), it would pass as0, and.slice()would hand the script an empty list again, with no error. - A refused query or path value gets
400. So far, the wall’s status rule covered bodies, and a body that breaks the rules still gets422. A query or path value the API refuses gets400instead, because the address itself is bad. So?grade=V14gets400, where the same grade in a body got422. The answer uses the API’s error shape, withz.flattenError()listing every problem by field indetails. - The handler uses the parsed data. After a successful
safeParse(), it filters and slices withresult.data, where the limit is already a number.
Everything in a URL arrives as text. Coerce the ones that mean numbers, keep the rest as strings, and don’t let an empty value slip through as 0.