|
| 1 | +import importProcedures from './import'; |
| 2 | +import getProcedureUpdates from '../graphql/queries/getProcedureUpdates'; |
| 3 | +import client from '../graphql/client'; |
| 4 | +import ProcedureModel from '../models/Procedure'; |
| 5 | + |
| 6 | +export default async (data) => { |
| 7 | + // Count local Data in groups |
| 8 | + const groups = await ProcedureModel.aggregate([{ |
| 9 | + // Group by Period & Type |
| 10 | + $group: { |
| 11 | + _id: { period: '$period', type: '$type' }, |
| 12 | + count: { $sum: 1 }, |
| 13 | + }, |
| 14 | + }, |
| 15 | + { |
| 16 | + // Group by Period |
| 17 | + $group: { |
| 18 | + _id: '$_id.period', |
| 19 | + types: { $push: { type: '$_id.type', count: '$count' } }, |
| 20 | + }, |
| 21 | + }, |
| 22 | + { |
| 23 | + // Rename _id Field to period |
| 24 | + $project: { _id: 0, period: '$_id', types: 1 }, |
| 25 | + }]); |
| 26 | + |
| 27 | + const update = []; |
| 28 | + await Promise.all(data.map(async (d) => { |
| 29 | + const period = parseInt(d.period, 10); |
| 30 | + const { type, countBefore, changedIds } = d.types.find(t => t.type === 'Gesetzgebung'); |
| 31 | + const group = groups.find(c => c.period === period); |
| 32 | + const localCount = group ? group.types |
| 33 | + .find(ct => ct.type === type).count : 0; |
| 34 | + // Append Changed IDs |
| 35 | + update.concat(changedIds); |
| 36 | + // Compare Counts Remote & Local |
| 37 | + if (countBefore > localCount) { |
| 38 | + // Find remote Procedure Updates |
| 39 | + const { data: { procedureUpdates } } = await client.query({ |
| 40 | + query: getProcedureUpdates, |
| 41 | + variables: { period, type }, |
| 42 | + }); |
| 43 | + // Find local Procedure Updates |
| 44 | + const localProcedureUpdates = await ProcedureModel |
| 45 | + .find({ period, type }, { procedureId: 1, lastUpdateDate: 1 }); |
| 46 | + // Compare |
| 47 | + procedureUpdates.forEach((pu) => { |
| 48 | + const localData = localProcedureUpdates.find(ld => ld.procedureId === pu.procedureId); |
| 49 | + if (!localData || new Date(localData.lastUpdateDate) < new Date(pu.updatedAt)) { |
| 50 | + update.push(pu.procedureId); |
| 51 | + } |
| 52 | + }); |
| 53 | + } |
| 54 | + })); |
| 55 | + |
| 56 | + // Splitt in Chunks & Update |
| 57 | + const chunkSize = 100; |
| 58 | + let updateCount = 0; |
| 59 | + let i = 0; |
| 60 | + for (i = 0; i < update.length; i += chunkSize) { |
| 61 | + const part = update.slice(i, i + chunkSize); |
| 62 | + updateCount += await importProcedures(part); // eslint-disable-line no-await-in-loop |
| 63 | + } |
| 64 | + |
| 65 | + return updateCount; |
| 66 | +}; |
0 commit comments