#How to validate all searchParams in a GET request?

3 messages · Page 1 of 1 (latest)

shadow meadow
#

I have a project that has a lot of route handlers, but I'm wondering if there's a way to efficiently check if all of the parameters are provided for a GET request.

This code works fine, but I'm repeating myself way too much. Also, I have several route handlers that require a lot of parameters like this, and I feel like there's a better way to do this.

export async function GET(request: NextRequest) {
    const { searchParams } = new URL(request.url);

    const stocksTicker = searchParams.get("stocksTicker");
    if (stocksTicker === null) {
      return new Response("Error: stocksTicker not provided", { status: 400 });
    }

    const multiplier = searchParams.get("multiplier");
    if (multiplier === null) {
        return new Response("Error: multiplier not provided", { status: 400 });
    }

    const timespan = searchParams.get("timespan");
    if (timespan === null) {
        return new Response("Error: timespan not provided", { status: 400 });
    }

    ...
limber marshBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)