Refactor PlansRepository to optimize data loading and enhance error handling

- Replaced the previous hydration logic with a new method, `loadChildrenForRows`, to efficiently load related data for plans in a single query.
- Implemented a `groupByPlanId` utility to organize related entities by plan ID, improving data retrieval performance.
- Updated error handling in the `getPlan` method to throw a `NotFoundException` if a plan is not found.
- Modified end-to-end tests to validate the new structure of the response, ensuring that related destinations are correctly included in the API output.
This commit is contained in:
shancheas
2026-09-01 19:25:19 +07:00
parent 6b3ddfcff9
commit 9428a983f5
2 changed files with 74 additions and 22 deletions
+56 -17
View File
@@ -79,9 +79,7 @@ export class PlansRepository {
.limit(filters.limit)
.offset(filters.offset);
return {
data: await this.hydrate(
rows.map((row) => this.toDomain(row, [], [], [])),
),
data: await this.loadChildrenForRows(this.db, rows),
total: Number(totalRows[0]?.total ?? 0),
};
}
@@ -340,20 +338,61 @@ export class PlansRepository {
executor: QueryExecutor,
row: PlanRow,
): Promise<Plan> {
const destinations = await executor
.select()
.from(planDestinations)
.where(eq(planDestinations.planId, row.id))
.orderBy(asc(planDestinations.sortOrder));
const invoices = await executor
.select()
.from(planInvoices)
.where(eq(planInvoices.planId, row.id));
const packingSlips = await executor
.select()
.from(planPackingSlips)
.where(eq(planPackingSlips.planId, row.id));
return this.hydrateOne(row, destinations, invoices, packingSlips);
const [plan] = await this.loadChildrenForRows(executor, [row]);
if (!plan) {
throw new NotFoundException('Plan not found');
}
return plan;
}
private async loadChildrenForRows(
executor: QueryExecutor,
rows: PlanRow[],
): Promise<Plan[]> {
if (rows.length === 0) {
return [];
}
const ids = rows.map((row) => row.id);
const [destinationRows, invoiceRows, packingSlipRows] = await Promise.all([
executor
.select()
.from(planDestinations)
.where(inArray(planDestinations.planId, ids))
.orderBy(asc(planDestinations.sortOrder)),
executor
.select()
.from(planInvoices)
.where(inArray(planInvoices.planId, ids)),
executor
.select()
.from(planPackingSlips)
.where(inArray(planPackingSlips.planId, ids)),
]);
const destinationsByPlan = this.groupByPlanId(destinationRows);
const invoicesByPlan = this.groupByPlanId(invoiceRows);
const packingByPlan = this.groupByPlanId(packingSlipRows);
return this.hydrate(
rows.map((row) =>
this.toDomain(
row,
destinationsByPlan.get(row.id) ?? [],
invoicesByPlan.get(row.id) ?? [],
packingByPlan.get(row.id) ?? [],
),
),
);
}
private groupByPlanId<T extends { planId: string }>(
rows: T[],
): Map<string, T[]> {
const ids = [...new Set(rows.map((row) => row.planId))];
return new Map(
ids.map((planId) => [
planId,
rows.filter((row) => row.planId === planId),
]),
);
}
private async replaceChildren(