Drizzle equivalent of `findFirstOrThrow`

Is there an analgous way to do this code in drizzle?
const data = await prisma.appData.findFirstOrThrow({}));
const data = await prisma.appData.findFirstOrThrow({}));
is the best path forward to manually throw errors? is this a planned feature?
3 Replies
Dan
Dan2y ago
You should just manually throw errors, yes
jakeleventhal
jakeleventhalOP2y ago
thanks, closing
Ni
Ni2d ago
Very much necroposting here but I wrote this helper for my tests and it does the job
import {
BuildQueryResult,
DBQueryConfig,
KnownKeysOnly,
TableRelationalConfig,
TablesRelationalConfig,
} from "drizzle-orm"
import { RelationalQueryBuilder } from "drizzle-orm/pg-core/query-builders/query"

export class FindFirstError extends Error {
constructor(config?: Record<string, unknown>) {
super(
`findFirst query yielded no results. Query config: ${JSON.stringify(config)}`
)
this.name = "FindFirstError"
}
}

export async function findFirstOrThrow<
TSchema extends TablesRelationalConfig,
TFields extends TableRelationalConfig,
TConfig extends DBQueryConfig<"one", TSchema, TFields>,
>(
table: RelationalQueryBuilder<TSchema, TFields>,
config?: KnownKeysOnly<TConfig, DBQueryConfig<"one", TSchema, TFields>>
): Promise<BuildQueryResult<TSchema, TFields, TConfig>> {
const result = await table.findFirst(config)

const isResult = (
value: BuildQueryResult<TSchema, TFields, TConfig> | undefined
): value is BuildQueryResult<TSchema, TFields, TConfig> => !!value

if (!isResult(result)) {
throw new FindFirstError(config)
}

return result
}
import {
BuildQueryResult,
DBQueryConfig,
KnownKeysOnly,
TableRelationalConfig,
TablesRelationalConfig,
} from "drizzle-orm"
import { RelationalQueryBuilder } from "drizzle-orm/pg-core/query-builders/query"

export class FindFirstError extends Error {
constructor(config?: Record<string, unknown>) {
super(
`findFirst query yielded no results. Query config: ${JSON.stringify(config)}`
)
this.name = "FindFirstError"
}
}

export async function findFirstOrThrow<
TSchema extends TablesRelationalConfig,
TFields extends TableRelationalConfig,
TConfig extends DBQueryConfig<"one", TSchema, TFields>,
>(
table: RelationalQueryBuilder<TSchema, TFields>,
config?: KnownKeysOnly<TConfig, DBQueryConfig<"one", TSchema, TFields>>
): Promise<BuildQueryResult<TSchema, TFields, TConfig>> {
const result = await table.findFirst(config)

const isResult = (
value: BuildQueryResult<TSchema, TFields, TConfig> | undefined
): value is BuildQueryResult<TSchema, TFields, TConfig> => !!value

if (!isResult(result)) {
throw new FindFirstError(config)
}

return result
}

Did you find this page helpful?