Theo
Theo

Reputation: 13

Next.js parse data-type from PostgreSQL

I'm new to Next.js and I am currently following the official tutorial. To spice it up, I decided to run PostgreSQL locally instead of using the @vercel/postgres SDK used in the tutorial. In the tutorial, they use the sql function of the SDK, which I have replaced by pool.query() from the node-postgres client. For most queries, this works fine and I am able to communicate with my local PostgreSQL database. However, I am having trouble adapting this code:

const data = await sql<Revenue>`SELECT * FROM revenue`;

What is it doing? From my understanding, <Revenue> is a type passed with the sql function, which I suppose is used to parse the data returned by @vercel/postgres.

How could I adapt my code to parse the <Revenue> data-type using node-postgres? Here is my current code:

const data = await pool.query(`SELECT * FROM revenue`);

For reference, here is the code I am trying to adapt (line 24 in data.ts). The <Revenue> type is defined in definitions.ts and the database content is in placeholder-data.js

Thank you for your help!

Upvotes: 0

Views: 301

Answers (1)

Jefim Kundzinovic
Jefim Kundzinovic

Reputation: 3

I also stumbled into this mess and personally I understand your need to get around without that Vercel Cloud Service.

So what I did to understand if stuff is working—and I see you are also hitting almost the same route:

const data = await pool.query(`SELECT * FROM revenue`);

console.info(data);

With the console command, I wanted to check what am I returning to understand if I can convert it into same meaningful type if needed. But I got lucky and achieved same result as in the tutorial chart view by just changing from sql<Revenue> to pool.query and it seems that the object that is returned is very similar.

This working mechanism might be just luckily a setup from the chart:

export default async function RevenueChart({
  revenue,
}: {
  revenue: Revenue[];

Where it conveniently still converts revenue into an array of Revenue Objects.

Upvotes: 0

Related Questions