Query Params
Reading the ?name=value pairs a client appends to the URL
Overview
Query params are read the same way path params are, using queryParam() instead of pathParam(). Nothing needs to be declared in paths — any client can append any query string to any path, so queryParam() is available on every resource regardless of what its paths look like.
Recommended Reading
- Read Handling Requests for how
paramsgets onto the request - Read Path Params for the other half of
params
Objectives
To gain familiarity with:
- reading a query param with
queryParam(); and - the caveat affecting the first parameter in a query string.
Reading a Query Param
Deno
import {
Resource,
type HTTPRequest,
} from "npm:@drashland/drash/modules/http.native.js";
class Users extends Resource {
public paths = ["/users"];
public GET(request: HTTPRequest) {
const page = request.params.queryParam("page");
return new Response(`page=${page}`);
}
}A param the client did not send comes back as undefined rather than throwing, so check the value instead of catching an error.
The First Parameter Caveat
queryParam() does not return the first query parameter. It is built from
new URLSearchParams(request.url), which parses the entire URL as a query
string rather than just the part after ?. The first parameter’s name is
absorbed into the URL prefix, so for
http://localhost:1447/users/1?sort=asc&page=2:
request.params.queryParam("sort"); // undefined
request.params.queryParam("page"); // "2"Every parameter after the first behaves correctly. Until this is fixed, read the query string yourself when you need the first parameter:
const sort = new URL(request.url).searchParams.get("sort");The workaround is worth reaching for whenever a resource reads a query param that a client might send on its own. A param that is always second in your own links is still first when someone types the URL by hand.
Verification
With a resource whose paths are ["/users"] running on localhost:1447:
curl "http://localhost:1447/users?page=2" -> page=undefined
curl "http://localhost:1447/users?x=1&page=2" -> page=2The first call returns undefined for the reason described above — page is the first parameter there, so its name is swallowed by the URL prefix. Adding any parameter ahead of it makes it read correctly.