Repository navigation
Repositories
Ports and adapters: where the database contract lives, how Prisma implements it, and how tests replace it. Status: current.
Routes never import Prisma. They call a port — a TypeScript interface in domain/ports/ — and
main.ts supplies the implementation through the Elysia context. That is what keeps the interface
layer testable without a database and what the layer lint enforces.
| Port | Methods | Prisma implementation | Used by |
|---|---|---|---|
CourseRepository |
findAll(filter?), findById(id)
|
prisma-course.repository.ts |
/v1/courses |
CourseUnitRepository |
findById(id), findByCourse(courseId)
|
prisma-course-unit.repository.ts |
/v1/courses/:id/units, /v1/course-units/:id
|
FacultyRepository |
findAll(), findByAcronym(acronym), findCoursesByFaculty(acronym, year?)
|
prisma-faculty.repository.ts |
/v1/faculties |
OccurrenceRepository |
findByCourseUnit(courseUnitId) |
prisma-occurrence.repository.ts |
/v1/course-units/:id/occurrences |
UserRepository |
upsertFromClaims(claims), findById(id)
|
user.repository.ts |
login |
SessionRepository |
issue(userId, ttlMs), resolve(token), revoke(token)
|
session.repository.ts |
auth middleware, login, logout |
IdentityProvider |
authorizationUrl({state}), exchangeCodeForUser(code)
|
sigarra-oidc.provider.ts |
OIDC login |
DevAuthenticator |
authenticate(username, password) |
sigarra-direct-auth.ts |
dev login |
The first six are bundled in Repositories and created by createRepositories(db). The two auth
adapters are constructed separately in main.ts, because they need config, not the database.
Every implementation is a factory that closes over the connection:
export function createCourseRepository({ db }: { db: Db }): CourseRepository {
return {
async findAll(filter = {}) { … },
async findById(id) { … },
}
}No inheritance, no decorators, no global singleton. The connection is injected once in main.ts,
which also makes the fakes trivial.
A repository knows nothing about HTTP. “Not found” is null; “no matches” is []. The route
decides that null means 404 course-not-found. Repositories may throw on corrupt data
(e.g. an invalid semester) — that is a bug and becomes a 500.
Ports import core/ types (AuthUser) and define their own entity shapes (Course, CourseUnit,
Occurrence, Faculty). They never expose Prisma row types or Db. The implementation maps rows to
the port type before returning.
The API promises an order, so the repository enforces it:
- faculties, courses, course units → acronym ascending;
- occurrences → year descending, then id ascending.
A test fake must mirror this, or route tests will pass while production disagrees.
The codebase uses the fluent API, not the classic prisma.model.findMany:
db.orm.public.Course.where({ id }).first()
db.orm.public.Faculty.orderBy((f) => f.acronym.asc()).all()
db.orm.public.Occurrence.where((o) => o.courseUnitId.eq(id))
.select('id', 'courseUnitId', 'courseId', 'year', 'ects', 'url', 'hash')
.orderBy([(o) => o.year.desc(), (o) => o.id.asc()])
.all()Rules that follow from the schema:
-
No implicit many-to-many.
FacultyCourse,SlotClassandSlotProfessorare explicit join tables; resolving a course's faculties always takes a second query. -
Select only what the API exposes. Rows carry
createdAt/updatedAt; returningrowwhole would leak them and rely on response stripping to save you. -
Branch instead of conditionally chaining.
selectCourseshas one branch per filter combination so Prisma keeps full types on every path, and returns[]immediately when anidsfilter is empty. -
Batch joins.
attachFacultiesreads the join table once for every course in the page and groups in memory, instead of one query per course. -
Use the database's atomic operations.
User.upserthandles two concurrent first logins in one statement; a read-then-create would make the second insert hit the primary key.
| File | Responsibility |
|---|---|
auth-user.mapper.ts |
Row → AuthUser; keeps role narrow, ignores extra columns |
course-mapper.ts |
toCourseRow, selectCourses, attachFaculties, loadCourses — the shared course read and faculty join |
prisma-course-unit.repository.ts |
Narrows semester: number → 1 | 2 at the boundary |
The course mapper is shared by both the course and faculty repositories so the FacultyCourse join
is implemented once. toAuthUser deliberately takes a narrow structural type: widening role to
string upstream would reintroduce as UserRole casts and lose compile-time safety when a new role
is added.
main.ts
createRepositories(db) // repositories/index.ts
├── createCourseRepository({ db })
├── createCourseUnitRepository({ db })
├── createFacultyRepository({ db })
├── createOccurrenceRepository({ db })
├── createUserRepository({ db })
└── createSessionRepository({ db })
.decorate('repositories', repositories)
Routes read repositories.courseRepository from the context. Their plugin types declare the slice
they need (decorator: { repositories: { courseRepository: CourseRepository } }) because Elysia does
not carry a parent plugin's decoration types into a standalone instance.
Tests call createApp({ repositories: { … } }); the spread overrides only the repositories they
care about. That is why createApp() boots without a database — the Prisma client is lazy until a
repository actually queries.
| Helper | What it fakes |
|---|---|
createFakeCourseRepository |
findAll with year/faculty filters, findById
|
createFakeFacultyRepository |
findAll, findByAcronym, findCoursesByFaculty via the course fixtures |
createFakeCourseUnitRepository |
findById, findByCourse (sorted by acronym) |
createFakeOccurrenceRepository |
findByCourseUnit, year desc then id asc |
createFakeUsers |
upsertFromClaims, findById
|
createFakeSessions |
Stateful tokens: tok-1 signed in, issue mints tok-N, revoke works |
createFakeIdentityProvider |
Redirect URL + fixed claims |
createFakeDevAuthenticator |
Configurable success/failure |
createCatalogApp / createTestAuthConfig
|
Wire the fakes into createApp()
|
Rules for fakes:
-
Mirror the contract, not a convenient subset. Same filters, same order, same
null/[]. -
Stay in
tests/interface/routes/support/. Do not declare a fake repository inside a route test — extendcatalog-test-utils.tsorauth-test-utils.tsinstead. - No network, no Prisma. A fake is an object literal; the test suite must run on a bare checkout.
- Add the method to the port with domain types and a doc comment stating the endpoint it serves.
- Implement it in
infrastructure/database/repositories/. - If it is a new repository: add it to
RepositoriesandcreateRepositories(db). - Use it from the route (or a use-case); keep the HTTP decision there.
- Add or extend the fake. If it is a new catalog repository, default it inside
createCatalogApp(). - Add route tests for the success shape, filters,
404and ordering. - Update the resource page and Adding an endpoint.
- Returning a raw row. Extra columns leak or fail the response schema; map explicitly.
-
Throwing
HttpErrorfrom a repository. It couples storage to transport. Returnnull. - Putting HTTP or Elysia types in a port. The domain must stay framework-free.
- Assuming implicit m2m. Prisma 8 has none; write the join.
-
Forgetting the empty-
idsguard.where id in []is a wasted query; return[]. -
One query per row. Batch the join, as
attachFacultiesdoes. - A fake with different ordering. Tests pass, production differs.
-
Importing
@/infrastructure/**frominterface/. Lint fails; use the context.
- Backend layers — the dependency rule
- Domain model — the tables these ports read
- Testing 🚧 — the fake-repository test pattern
- Adding an endpoint — the full checklist
- Database guide — contract and migrations
Last verified: 2026-10-27