-
Notifications
You must be signed in to change notification settings - Fork 58
/
Copy pathgenerate-knowledge-element-snapshots-for-campaigns.js
128 lines (111 loc) · 4.29 KB
/
generate-knowledge-element-snapshots-for-campaigns.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
import * as url from 'node:url';
import yargs from 'yargs';
import { disconnect, knex } from '../../db/knex-database-connection.js';
import * as knowledgeElementSnapshotRepository from '../../src/prescription/campaign/infrastructure/repositories/knowledge-element-snapshot-repository.js';
import { KnowledgeElementCollection } from '../../src/prescription/shared/domain/models/KnowledgeElementCollection.js';
import { AlreadyExistingEntityError } from '../../src/shared/domain/errors.js';
import * as knowledgeElementRepository from '../../src/shared/infrastructure/repositories/knowledge-element-repository.js';
import { PromiseUtils } from '../../src/shared/infrastructure/utils/promise-utils.js';
const DEFAULT_MAX_SNAPSHOT_COUNT = 5000;
const DEFAULT_CONCURRENCY = 3;
function _validateAndNormalizeMaxSnapshotCount(maxSnapshotCount) {
if (isNaN(maxSnapshotCount)) {
maxSnapshotCount = DEFAULT_MAX_SNAPSHOT_COUNT;
}
if (maxSnapshotCount <= 0 || maxSnapshotCount > 50000) {
throw new Error(`Nombre max de snapshots ${maxSnapshotCount} ne peut pas être inférieur à 1 ni supérieur à 50000.`);
}
return maxSnapshotCount;
}
function _validateAndNormalizeConcurrency(concurrency) {
if (isNaN(concurrency)) {
concurrency = DEFAULT_CONCURRENCY;
}
if (concurrency <= 0 || concurrency > 10) {
throw new Error(`Concurrent ${concurrency} ne peut pas être inférieur à 1 ni supérieur à 10.`);
}
return concurrency;
}
function _validateAndNormalizeArgs({ concurrency, maxSnapshotCount }) {
const finalMaxSnapshotCount = _validateAndNormalizeMaxSnapshotCount(maxSnapshotCount);
const finalConcurrency = _validateAndNormalizeConcurrency(concurrency);
return {
maxSnapshotCount: finalMaxSnapshotCount,
concurrency: finalConcurrency,
};
}
async function getEligibleCampaignParticipations(maxSnapshotCount) {
return knex('campaign-participations')
.select('campaign-participations.id', 'campaign-participations.userId', 'campaign-participations.sharedAt')
.leftJoin(
'knowledge-element-snapshots',
'knowledge-element-snapshots.campaignParticipationId',
'campaign-participations.id',
)
.whereNotNull('campaign-participations.sharedAt')
.where((qb) => {
qb.whereNull('knowledge-element-snapshots.campaignParticipationId');
})
.orderBy('campaign-participations.id')
.limit(maxSnapshotCount);
}
async function generateKnowledgeElementSnapshots(
campaignParticipationData,
concurrency,
dependencies = { knowledgeElementRepository, knowledgeElementSnapshotRepository },
) {
return PromiseUtils.map(
campaignParticipationData,
async (campaignParticipation) => {
const { userId, sharedAt, id } = campaignParticipation;
const knowledgeElements = await dependencies.knowledgeElementRepository.findUniqByUserId({
userId,
limitDate: sharedAt,
});
try {
await dependencies.knowledgeElementSnapshotRepository.save({
snapshot: new KnowledgeElementCollection(knowledgeElements).toSnapshot(),
campaignParticipationId: id,
});
} catch (err) {
if (!(err instanceof AlreadyExistingEntityError)) {
throw err;
}
}
},
{ concurrency },
);
}
const modulePath = url.fileURLToPath(import.meta.url);
const isLaunchedFromCommandLine = process.argv[1] === modulePath;
async function main() {
const commandLineArgs = yargs
.option('maxSnapshotCount', {
description: 'Nombre de snapshots max. à générer.',
type: 'number',
default: DEFAULT_MAX_SNAPSHOT_COUNT,
})
.option('concurrency', {
description: 'Concurrence',
type: 'number',
default: DEFAULT_CONCURRENCY,
})
.help().argv;
const { maxSnapshotCount, concurrency } = _validateAndNormalizeArgs(commandLineArgs);
const campaignParticipationData = await getEligibleCampaignParticipations(maxSnapshotCount);
await generateKnowledgeElementSnapshots(campaignParticipationData, concurrency);
}
(async () => {
if (isLaunchedFromCommandLine) {
try {
await main();
} catch (error) {
console.error('\x1b[31mErreur : %s\x1b[0m', error.message);
yargs.showHelp();
process.exitCode = 1;
} finally {
await disconnect();
}
}
})();
export { generateKnowledgeElementSnapshots, getEligibleCampaignParticipations };