Next.js Discord

Discord Forum

Conditionally update info in Vercel PostgresSQL?

Unanswered
Greenish Elaenia posted this in #help-forum
Open in Discord
Greenish ElaeniaOP
I have this api route that current works. I want to change it to still update if the user doesnt provide all the information. None of the 3 columns are NOT NULL.
For example, if the user doesn't update the COUNT column, it stays the default 0 (zero).

import { sql } from '@vercel/postgres';
import { NextResponse } from 'next/server';

export async function GET(request: Request) {
const { searchParams } = new URL(request.url);
const app = searchParams.get('app');
const name = searchParams.get('name');
const count = searchParams.get('count');

try {
if (!app | | !name | | !count) throw new Error('app, name, and count required');
const result =
await sqlINSERT INTO Counters ( app, name, count) VALUES ( ${app}, ${name}, ${count} );;
return NextResponse.json({ result }, { status: 200, statusText: "OK" });
} catch (error) {
// Convert Error object to string to get 'app, name, and count required'
return NextResponse.json({ result: {} }, { status: 500, statusText: String(error) });
}
}

For example, if the user didn't provide 'count', then the sql would be

await sqlINSERT INTO Counters ( app, name) VALUES ( ${app}, ${name});

Since it's only 3 variables, I could in theory just have the sql repeat 3 times.
However, if this was the Users table, then there would be way too many variants of the sql to hard code, due to the Users table having maybe 15+ columns

How do I dynamically add or not add variables to a sql?

2 Replies

Toyger
if you have default values in your table you can just pass DEFAULT
not sure how it works with vercel sql function, but probably something like that
const result =
      await sql
        INSERT INTO Counters (
            app, 
            name, 
            count) 
        VALUES (
            ${app ? app : 'DEFAULT'},
            ${name ? name : 'DEFAULT'},
            ${count ? count : 'DEFAULT'}
        );
Greenish ElaeniaOP
So write ternary for optional variables? Lemme try that