refactor(db): keep the touched files within their size baselines

The users identity guard moves to repositories/_shared/user-identity.ts
(Users.repository.ts re-exports UserIdentityTakenError), the flag text pass
of the entity generator to scripts/generate-entities-flags.ts, and the
Wallet pass query takes the repository's EntityManager. The size baseline
of Users.repository.ts is lowered to what it holds now (1445 to 1421); a
few exports only their own file used are no longer exported.
This commit is contained in:
Maurice
2026-11-17 12:22:22 +01:00
parent 9e5379d092
commit a26db47cb6
11 changed files with 96 additions and 92 deletions
@@ -8,7 +8,7 @@ import { REFUSAL } from '../../legacy-baseline';
*/
/** The PostgreSQL majors TREK supports and CI runs: the oldest and the newest. */
export const SUPPORTED_SERVER_MAJORS = { oldest: 14, newest: 18 } as const;
const SUPPORTED_SERVER_MAJORS = { oldest: 14, newest: 18 } as const;
/**
* True when the current role is a superuser or may run programs or write
@@ -7,7 +7,7 @@ import { accommodationIdMatches } from './_shared/reservation-accommodation';
import { publicReservationExpr, publicStayExists, type ReservationVisibilityKyselyDB } from './_shared/reservation-visibility';
import type { DayAssignmentRow } from './day-assignment-rows';
import { TrekRepository } from './_shared/trek-repository';
import { passContextQuery, type PassContextDB } from './_shared/reservation-pass-context';
import { passContextQuery } from './_shared/reservation-pass-context';
import { originColumnValues, type ReservationOriginColumns } from './_shared/reservation-origin-columns';
import { idByExternalQuery, joinedReservationQuery, type ReservationJoinDB } from './_shared/reservation-joined-query';
import type { DB } from '../kysely/db';
@@ -350,9 +350,7 @@ type FlightsMissingEndpointsKyselyDB = Pick<DB, 'reservations' | 'reservation_en
export class ReservationsRepository extends TrekRepository<Reservations> {
// For its Wallet pass (_shared/reservation-pass-context.ts).
findPassContext(id: number, tripId: number) {
return passContextQuery(this.kysely<PassContextDB>(), this.getEntityManager().getPlatform(), id, tripId);
}
findPassContext(id: number, tripId: number) { return passContextQuery(this.getEntityManager(), id, tripId); }
private joinedQuery() {
return joinedReservationQuery(this.kysely<ReservationJoinDB>(), this.getEntityManager().getPlatform());
@@ -792,10 +792,9 @@ export class TripsRepository extends TrekRepository<Trips> {
* FROMs has no single alias to chain a `.select()`/`.where()` off (unlike
* `accessibleTripsQuery`'s single-FROM join), so this is Kysely
* (`this.kysely()`, the same escape hatch `tripSelectQuery`'s own
* docstring documents). The two literal branches are `eb.lit(1)`/`eb.lit(0)`,
* written into the statement as integers: a bound `eb.val(1)` reaches
* Postgres untyped, and a UNION column of untyped values comes back as
* text ('1'), which the public API's `is_owner === 1` never matched.
* docstring documents). The literals are `eb.lit(1)`/`eb.lit(0)`, inline integers: a bound
* `eb.val(1)` reaches Postgres untyped, and a UNION column of untyped values comes back
* as text ('1'), which the public API's `is_owner === 1` never matched.
*/
async listTravellerUsernames(trip_id: number): Promise<TravellerUsernameRow[]> {
const owner = this.kysely<TravellerUsernameKyselyDB>()
+3 -35
View File
@@ -2,7 +2,9 @@ import { Users } from '../entities/Users.entity';
import { toRow, type AssertRowKeys } from './_shared/rows';
import { coalesce, columnIncrementedBy, currentTimestamp, lower, lowerParam } from '../dialect/sql-functions';
import { TrekRepository } from './_shared/trek-repository';
import { uniqueViolationKey } from '../dialect/driver-errors';
import { guardIdentity } from './_shared/user-identity';
export { UserIdentityTakenError } from './_shared/user-identity';
/**
* The three third-party keys that belong to the instance rather than to a
@@ -251,40 +253,6 @@ export interface NewAdminUserRow {
role: string;
}
/**
* A write the database refused because another account already holds that
* email address (in any case, `idx_users_email_lower`) or username. The
* services check first and answer 409; this is the same answer for the write
* that lost a race against another one, instead of a 500.
*/
export class UserIdentityTakenError extends Error {
constructor(readonly field: 'email' | 'username') {
super(`${field} already taken`);
this.name = 'UserIdentityTakenError';
}
}
/**
* The keys that name the email and the username in a unique violation: SQLite
* names the column (`users.email`) or the index, Postgres the constraint
* (`users_email_unique`, `users_username_unique`) or the index
* (`idx_users_email_lower`).
*/
const EMAIL_KEY = /users\.email|users_email_unique|idx_users_email/;
const USERNAME_KEY = /users\.username|users_username_unique/;
/** Runs a users write, turning a unique violation on email or username into {@link UserIdentityTakenError}. */
async function guardIdentity<T>(write: () => Promise<T>): Promise<T> {
try {
return await write();
} catch (err) {
const key = uniqueViolationKey(err);
if (key !== null && EMAIL_KEY.test(key)) throw new UserIdentityTakenError('email');
if (key !== null && USERNAME_KEY.test(key)) throw new UserIdentityTakenError('username');
throw err;
}
}
/** AD11 (`admin.service.ts#updateUser`, inside `uow.transactional`) — the columns the legacy COALESCE-shaped UPDATE can touch; a key the caller omits is left unchanged, the same net effect as binding NULL into `COALESCE(?, column)`. */
export interface AdminEditPatch {
username?: string;
@@ -1,11 +1,9 @@
import type { DB } from '../../kysely/db';
import { accommodationIdMatches } from './reservation-accommodation';
import type { Platform } from '@mikro-orm/core';
import type { Kysely } from 'kysely';
import type { SqlEntityManager } from '@mikro-orm/sql';
/** The tables `passContextQuery` reads. */
export type PassContextDB = Pick<DB, 'reservations' | 'trips' | 'places' | 'day_accommodations'>;
type PassContextDB = Pick<DB, 'reservations' | 'trips' | 'places' | 'day_accommodations'>;
/** What a booking's Wallet pass needs beyond the booking: where it is, and the trip's name. */
export interface ReservationPassContext {
@@ -19,15 +17,17 @@ export interface ReservationPassContext {
* The trip's title and the place a booking is at (its own place, else its
* stay's), for its Apple Wallet pass (`ReservationsRepository.findPassContext`).
* Scoped to the trip, so a booking of another trip reads as none. Kept out of
* the repository file, which is at its size baseline.
* the repository file, which is at its size baseline. `em` is the repository's
* own, which has checked the request context.
*/
export async function passContextQuery(
kysely: Kysely<PassContextDB>,
platform: Platform,
em: SqlEntityManager,
id: number,
trip_id: number,
): Promise<ReservationPassContext | undefined> {
const row = await kysely
const platform = em.getPlatform();
const row = await em
.getKysely<PassContextDB>()
.selectFrom('reservations as r')
.innerJoin('trips as t', 't.id', 'r.trip_id')
.leftJoin('places as p', 'p.id', 'r.place_id')
@@ -0,0 +1,35 @@
import { uniqueViolationKey } from '../../dialect/driver-errors';
/**
* A write the database refused because another account already holds that
* email address (in any case, `idx_users_email_lower`) or username. The
* services check first and answer 409; this is the same answer for the write
* that lost a race against another one, instead of a 500.
*/
export class UserIdentityTakenError extends Error {
constructor(readonly field: 'email' | 'username') {
super(`${field} already taken`);
this.name = 'UserIdentityTakenError';
}
}
/**
* The keys that name the email and the username in a unique violation: SQLite
* names the column (`users.email`) or the index, Postgres the constraint
* (`users_email_unique`, `users_username_unique`) or the index
* (`idx_users_email_lower`).
*/
const EMAIL_KEY = /users\.email|users_email_unique|idx_users_email/;
const USERNAME_KEY = /users\.username|users_username_unique/;
/** Runs a users write, turning a unique violation on email or username into {@link UserIdentityTakenError}. */
export async function guardIdentity<T>(write: () => Promise<T>): Promise<T> {
try {
return await write();
} catch (err) {
const key = uniqueViolationKey(err) ?? '';
if (EMAIL_KEY.test(key)) throw new UserIdentityTakenError('email');
if (USERNAME_KEY.test(key)) throw new UserIdentityTakenError('username');
throw err;
}
}