neondatabase / serverless

Connect to Neon PostgreSQL from serverless/worker/edge functions
https://www.npmjs.com/package/@neondatabase/serverless
MIT License
343 stars 13 forks source link

How to type (if posible) a `sql` query response ? #59

Closed daguitosama closed 5 months ago

daguitosama commented 8 months ago

Im reading the examples and documentation on how to use the client you get out of neon(DB_URL); but have not found any clear way to type the result of runing a query, like for instance, the way postgres.js folks do it:


type User = {username: string, id: number};

const rows = await sql<User[]>`select * from users;`;
// now TS knows what's comming back of the query on those rows

Is posible doing that typing ?

If not, i think would be a wonderful adition 😂

jawj commented 7 months ago

Currently this is not supported.

However, you could use a tool like Kysely, Zapatos or Drizzle on top of the driver to achieve this.

robreiss commented 6 months ago

I just wrote a quick hack. It probably breaks down during edge cases (arrayMode etc), but worked for the couple db calls I do from the edge.

import { neon } from "@neondatabase/serverless";

const sql = neon(process.env.NEON_DB_URL!);

export async function sqlNeon<T>(
  query: TemplateStringsArray,
  ...params: any[]
): Promise<T> {
  const result = await sql(query, ...params);
  return result as T;
}

you could also just do something like:

const rows = (await sql`select * from users;`) as User[];