Select One and Only One or Throw #1499
Unanswered
JadenSWang
asked this question in
Q&A
Replies: 2 comments 6 replies
-
Drizzle doesn't have this feature just yet but a workaround would look something like this: // Define this helper somewhere in your codebase:
const takeUniqueOrThrow = <T extends any[]>(values: T): T[number] => {
if (values.lenght !== 1) throw new Error("Found non unique or inexistent value")
return values[0]!
}
// Use it in a query as follows:
const user = await db.select().from(users).where(eq(users.id, userId)).then(takeUniqueOrThrow);
// ^? const user: { id: string; name: string; ... } |
Beta Was this translation helpful? Give feedback.
6 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Is there anything in drizzle-orm's toolkit which allows you to query and select for only one item and throw an error if multiple or zero results are returned? I'm in the middle of migrating from a strange mix of stored procedures and quite often do I find myself checking if result > 1 and not 0.
I imagine this could be done even quicker with the use of UNIQUE fields.
Beta Was this translation helpful? Give feedback.
All reactions