Skip to content

Repositories

Francisca Portugal edited this page Oct 27, 2026 · 1 revision

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.

The ports

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.

Conventions

Factories, not classes

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.

Return null / [], never throw HTTP

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.

Domain types in, domain types out

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.

Ordering is part of the contract

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.

Prisma 8 specifics

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, SlotClass and SlotProfessor are explicit join tables; resolving a course's faculties always takes a second query.
  • Select only what the API exposes. Rows carry createdAt / updatedAt; returning row whole would leak them and rely on response stripping to save you.
  • Branch instead of conditionally chaining. selectCourses has one branch per filter combination so Prisma keeps full types on every path, and returns [] immediately when an ids filter is empty.
  • Batch joins. attachFaculties reads 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.upsert handles two concurrent first logins in one statement; a read-then-create would make the second insert hit the primary key.

Mappers

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.

Wiring

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.

Fakes

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 — extend catalog-test-utils.ts or auth-test-utils.ts instead.
  • No network, no Prisma. A fake is an object literal; the test suite must run on a bare checkout.

Adding a method or repository

  1. Add the method to the port with domain types and a doc comment stating the endpoint it serves.
  2. Implement it in infrastructure/database/repositories/.
  3. If it is a new repository: add it to Repositories and createRepositories(db).
  4. Use it from the route (or a use-case); keep the HTTP decision there.
  5. Add or extend the fake. If it is a new catalog repository, default it inside createCatalogApp().
  6. Add route tests for the success shape, filters, 404 and ordering.
  7. Update the resource page and Adding an endpoint.

Pitfalls

  • Returning a raw row. Extra columns leak or fail the response schema; map explicitly.
  • Throwing HttpError from a repository. It couples storage to transport. Return null.
  • 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-ids guard. where id in [] is a wasted query; return [].
  • One query per row. Batch the join, as attachFaculties does.
  • A fake with different ordering. Tests pass, production differs.
  • Importing @/infrastructure/** from interface/. Lint fails; use the context.

See also


Last verified: 2026-10-27

Clone this wiki locally