From d57aedc5d371e3a224494c4baef69edf6dcab3b3 Mon Sep 17 00:00:00 2001 From: "Torsten Schulz (local)" Date: Wed, 4 Feb 2026 15:20:40 +0100 Subject: [PATCH] Refactor vehicle loading in FalukantService: Update logic to load vehicle types and transports using separate queries, improving performance and preventing EagerLoadingError. Simplify data retrieval by mapping vehicle types and organizing transports by vehicle ID, enhancing code clarity and efficiency. --- backend/services/falukantService.js | 37 +++++++++++++++++++---------- 1 file changed, 24 insertions(+), 13 deletions(-) diff --git a/backend/services/falukantService.js b/backend/services/falukantService.js index a3841c5..3d5fc70 100644 --- a/backend/services/falukantService.js +++ b/backend/services/falukantService.js @@ -777,21 +777,32 @@ class FalukantService extends BaseService { const vehicles = await Vehicle.findAll({ where, - include: [ - { - model: VehicleType, - as: 'type', - attributes: ['id', 'tr', 'capacity', 'transportMode', 'speed', 'buildTimeMinutes', 'cost'], - }, - { - model: Transport, - as: 'transports', - attributes: ['id', 'sourceRegionId', 'targetRegionId'], - required: false, - }, - ], + attributes: ['id', 'vehicleTypeId', 'regionId', 'condition', 'availableFrom'], order: [['availableFrom', 'ASC'], ['id', 'ASC']], }); + const vehicleIds = vehicles.map(v => v.id); + const typeIds = [...new Set(vehicles.map(v => v.vehicleTypeId))]; + const [types, transports] = await Promise.all([ + typeIds.length ? VehicleType.findAll({ + where: { id: typeIds }, + attributes: ['id', 'tr', 'capacity', 'transportMode', 'speed', 'buildTimeMinutes', 'cost'], + }) : [], + vehicleIds.length ? Transport.findAll({ + where: { vehicleId: vehicleIds }, + attributes: ['id', 'vehicleId', 'sourceRegionId', 'targetRegionId'], + }) : [], + ]); + const typeMap = Object.fromEntries(types.map(t => [t.id, t])); + const transportsByVehicle = transports.reduce((acc, t) => { + const vid = t.vehicleId; + if (!acc[vid]) acc[vid] = []; + acc[vid].push(t); + return acc; + }, {}); + for (const v of vehicles) { + v.setDataValue('type', typeMap[v.vehicleTypeId] || null); + v.setDataValue('transports', transportsByVehicle[v.id] || []); + } const now = new Date(); const branchRegionId = regionId ? parseInt(regionId, 10) : undefined;