porsager / postgres

Postgres.js - The Fastest full featured PostgreSQL client for Node.js, Deno, Bun and CloudFlare
The Unlicense
7.42k stars 271 forks source link

Return Single Object Instead of Array? #717

Closed chauhankiran closed 11 months ago

chauhankiran commented 11 months ago

Consider the following query.

  return await sql`
    select
      *
    from users
    where
      email = ${email} and password = ${password}
  `;

This will return a single user.

And there always be scenario where we're interested to fetch only single row than multiple row results. So, it there a way that we can only return just a single object ({}) instead array of object ([{}])? As of now, I need to write like user[0].id instead of user.id.

porsager commented 11 months ago

Destructuring for the win 😉

const [user] = await sql`...`
// user.id

And if you don't want the temporary variable you can do destructuring in .then like this:

return await sql`...`.then(([x]) => x)

And going further a utility function is so simple to have that increasing the surface api of this library is not worth it:

const first = ([x]) => x

const user = first(await sql`...`)
// or
const user = await sql`...`.then(first)