Getting Started
getOr404
The simplest utility -- await a query and throw a SvelteKit 404 if the result is null or undefined.
import { getOr404 } from '@repo/db'
const user = await getOr404(
db.query.users.findFirst({ where: eq(users.id, params.id) })
)
// user is guaranteed non-null here; 404 thrown otherwise
Basic Repository
Create a repository by extending the Repository class. Pass your db context getter to the constructor.
import { Repository } from '@repo/db'
import { eq } from 'drizzle-orm'
class UserRepository extends Repository<typeof getDbContext> {
async getById(id: string) {
const { db, users } = await this.getDbContext()
return db.query.users.findFirst({ where: eq(users.id, id) })
}
async list() {
const { db, users } = await this.getDbContext()
return db.query.users.findMany()
}
}
const userRepo = new UserRepository(getDbContext)
// Use it
const user = await getOr404(userRepo.getById('abc'))
The repository's getDbContext function returns both the db instance and the schema tables, so you can destructure them directly.
Swapping Database Context
Use withDb to create a copy of the repository bound to a different database context (e.g. inside a transaction):
await db.transaction(async (tx) => {
const txRepo = userRepo.withDb(() => ({ db: tx, ...schema }))
await txRepo.getById('abc')
})