11import { Argument , Command } from 'commander' ;
22
3+ import { asyncFilter , removeDuplicatesForProperty } from '../shared/array' ;
34import { getCsvContent } from '../shared/csv' ;
4- import { insertUsers , register } from '../shared/db' ;
5+ import { getUsersByRole , insertUsers } from '../shared/db' ;
56import { validateEnv } from '../shared/env' ;
67import { createLogger } from '../shared/logger' ;
7- import { ParticipantCsvRow , RegisterDTO , User , userRoles } from '../shared/models' ;
8- import { transformToMatchClass } from '../shared/object' ;
8+ import { CreateUserDTO , ParticipantCsvRow , userRoles } from '../shared/models' ;
9+ import { filterInvalid , transformAndValidate , transformToMatchClass } from '../shared/object' ;
910
1011const logger = createLogger ( 'register-participants' ) ;
1112
@@ -20,27 +21,37 @@ export const registerParticipants = (program: Command) => {
2021
2122 const rows = await getCsvContent ( csvPath ) ;
2223 const participantsRows = await Promise . all ( rows . map ( transformToMatchClass ( ParticipantCsvRow ) ) ) ;
24+ const correctParticipantsRows = await asyncFilter ( participantsRows , filterInvalid ( ParticipantCsvRow ) ) ;
2325
24- const participants : User [ ] = [ ] ;
26+ const currentParticipants = await getUsersByRole ( userRoles . participant ) ;
27+ const currentParticipantsEmails = currentParticipants . map ( ( { email } ) => email ) ;
2528
26- logger . debug ( 'Iterating through parsed rows ' ) ;
29+ logger . debug ( 'Filtering emails that are already added to the database ' ) ;
2730
28- for ( const { email, firstName, lastName } of participantsRows ) {
29- const registerDto = await transformToMatchClass ( RegisterDTO ) ( { email } ) ;
30- const userId = await register ( registerDto ) ;
31- const participant = await transformToMatchClass ( User ) ( {
32- ...registerDto ,
33- id : userId ,
34- name : `${ firstName } ${ lastName } ` ,
35- role : userRoles . participant ,
36- } ) ;
31+ const participantsRowsToAdd = correctParticipantsRows . filter ( ( { email } ) => {
32+ if ( currentParticipantsEmails . includes ( email ) ) {
33+ logger . debug ( `Participant with email ${ email } already exists in the database` ) ;
3734
38- participants . push ( participant ) ;
39- }
35+ return false ;
36+ }
4037
41- logger . debug ( 'Iteration through parsed rows finished' ) ;
38+ return true ;
39+ } ) ;
4240
43- await insertUsers ( participants ) ;
41+ logger . debug ( 'Mapping ParticipantCsvRows to CreateUserDTOs' ) ;
42+
43+ const createUserDTOs = await Promise . all (
44+ participantsRowsToAdd . map ( ( { email, firstName, lastName } ) =>
45+ transformAndValidate ( CreateUserDTO ) ( {
46+ email,
47+ firstName,
48+ lastName,
49+ role : userRoles . participant ,
50+ } ) ,
51+ ) ,
52+ ) ;
53+
54+ await insertUsers ( removeDuplicatesForProperty ( createUserDTOs , 'email' ) ) ;
4455 } catch ( ex ) {
4556 logger . error ( ex ) ;
4657 }
0 commit comments