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.

This commit is contained in:
Torsten Schulz (local)
2026-02-04 15:20:40 +01:00
parent 109a640fe2
commit d57aedc5d3

View File

@@ -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;