Skip to content

Commit

Permalink
[TECH] Remplacer Bluebird mapSeries par des fonctions natives (#9959)
Browse files Browse the repository at this point in the history
  • Loading branch information
bpetetot authored Sep 2, 2024
1 parent 913ffef commit 14f7a04
Show file tree
Hide file tree
Showing 50 changed files with 352 additions and 319 deletions.
6 changes: 3 additions & 3 deletions api/db/database-builder/database-builder.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
/* eslint-disable knex/avoid-injections */
import bluebird from 'bluebird';
import _ from 'lodash';

import { databaseBuffer } from './database-buffer.js';
Expand Down Expand Up @@ -97,12 +96,13 @@ class DatabaseBuilder {
}
const dirtyTablesSequencesInfo = await this._getSequencesInfo(dirtyTables);

return bluebird.mapSeries(dirtyTablesSequencesInfo, async ({ tableName, sequenceName }) => {
for (const dirtyTablesSequence of dirtyTablesSequencesInfo) {
const { tableName, sequenceName } = dirtyTablesSequence;
const sequenceRestartAtNumber = (await this._getTableMaxId(tableName)) + 1;
if (sequenceRestartAtNumber !== 0) {
await this.knex.raw(`ALTER SEQUENCE "${sequenceName}" RESTART WITH ${sequenceRestartAtNumber};`);
}
});
}
}

async _getSequencesInfo(dirtyTables) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import bluebird from 'bluebird';
import _ from 'lodash';

const up = async function (knex) {
Expand All @@ -16,13 +15,13 @@ const up = async function (knex) {
return [badgeId, partnerCompetenceIds];
});

await bluebird.mapSeries(badgesWithPartnerCompetences, async (badgeWithPartnerCompetences) => {
for (const badgeWithPartnerCompetences of badgesWithPartnerCompetences) {
const badgeId = badgeWithPartnerCompetences[0];
const partnerCompetenceIds = badgeWithPartnerCompetences[1];
await knex('badge-criteria')
.update({ partnerCompetenceIds, scope: 'SomePartnerCompetences' })
.where({ badgeId, scope: 'EveryPartnerCompetence' });
});
}
};

const down = function () {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ const COMPLEMENTARY_CERTIFICATION_COURSE_ID_COLUMN = 'complementaryCertification
const CERTIFICATION_COURSE_ID = 'certificationCourseId';
import lodash from 'lodash';
const { uniqBy } = lodash;
import bluebird from 'bluebird';

import { badges } from '../constants.js';
const {
Expand Down Expand Up @@ -52,14 +51,14 @@ const up = async function (knex) {
const complementaryCertifCourseIdForComplementaryCertifCourseResultIds =
await _getComplementaryCertifCourseIdForComplementaryCertifCourseResultId();

return bluebird.mapSeries(
complementaryCertifCourseIdForComplementaryCertifCourseResultIds,
async ({ complementaryCertificationCourseResultId, complementaryCertificationCourseId }) => {
await knex(COMPLEMENTARY_CERTIFICATION_COURSE_RESULTS_TABLE)
.update(COMPLEMENTARY_CERTIFICATION_COURSE_ID_COLUMN, complementaryCertificationCourseId)
.where({ id: complementaryCertificationCourseResultId });
},
);
for (const complementaryCertifCourse of complementaryCertifCourseIdForComplementaryCertifCourseResultIds) {
const { complementaryCertificationCourseResultId, complementaryCertificationCourseId } =
complementaryCertifCourse;

await knex(COMPLEMENTARY_CERTIFICATION_COURSE_RESULTS_TABLE)
.update(COMPLEMENTARY_CERTIFICATION_COURSE_ID_COLUMN, complementaryCertificationCourseId)
.where({ id: complementaryCertificationCourseResultId });
}
}

async function _addMissingComplementaryCertificationCourses() {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import bluebird from 'bluebird';

const TEMPLATE_TABLE_NAME = 'target-profile-templates';
const OLD_TEMPLATE_TUBES_TABLE_NAME = 'target-profile-templates_tubes';
const TARGET_PROFILE_TUBES_TABLE_NAME = 'target-profile_tubes';
Expand Down Expand Up @@ -45,12 +43,13 @@ const down = async function (knex) {

const results = await knex(TARGET_PROFILE_TUBES_TABLE_NAME).distinct('targetProfileId');

await bluebird.mapSeries(results, async ({ targetProfileId }) => {
for (const targetProfiles of results) {
const { targetProfileId } = targetProfiles;
const [{ id: targetProfileTemplateId }] = await knex(TEMPLATE_TABLE_NAME).insert({}).returning('id');

await knex(TARGET_PROFILE_TABLE_NAME).update({ targetProfileTemplateId }).where({ id: targetProfileId });
await knex(TARGET_PROFILE_TUBES_TABLE_NAME).update({ targetProfileTemplateId }).where({ targetProfileId });
});
}

await knex.schema.table(TARGET_PROFILE_TUBES_TABLE_NAME, (t) => {
t.dropNullable('targetProfileTemplateId');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,6 @@ const {
PIX_EMPLOI_CLEA_V3,
} = badges.keys;

import bluebird from 'bluebird';

const up = async function (knex) {
await knex.schema.table(TABLE_NAME, function (table) {
table.string(COLUMN_NAME);
Expand Down Expand Up @@ -83,7 +81,9 @@ const up = async function (knex) {
},
];

await bluebird.mapSeries(data, addImageUrlForBadgeKey);
for (const badgeImage of data) {
await addImageUrlForBadgeKey(badgeImage);
}

await knex.schema.alterTable(TABLE_NAME, function (table) {
table.string(COLUMN_NAME).notNullable().alter();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,6 @@ const {
PIX_EMPLOI_CLEA_V3,
} = badges.keys;

import bluebird from 'bluebird';

const up = async function (knex) {
await knex.schema.table(TABLE_NAME, function (table) {
table.string(COLUMN_NAME);
Expand Down Expand Up @@ -84,7 +82,9 @@ const up = async function (knex) {
},
];

await bluebird.mapSeries(data, addLabelForBadgeKey);
for (const badgeLabel of data) {
await addLabelForBadgeKey(badgeLabel);
}

await knex.schema.alterTable(TABLE_NAME, function (table) {
table.string(COLUMN_NAME).notNullable().alter();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import bluebird from 'bluebird';
const TABLE_NAME = 'complementary-certification-courses';
const COLUMN = 'complementaryCertificationBadgeId';

Expand All @@ -18,10 +17,11 @@ const up = async function (knex) {
)
.select('complementary-certification-courses.id', 'complementary-certification-course-results.partnerKey');

await bluebird.mapSeries(complementaryCertificationCourses, async function ({ id, partnerKey }) {
for (const complementaryCertificationCourse of complementaryCertificationCourses) {
const { id, partnerKey } = complementaryCertificationCourse;
const complementaryCertificationBadgeId = complementaryCertificationBadges.find(({ key }) => key === partnerKey).id;
await knex(TABLE_NAME).update(COLUMN, complementaryCertificationBadgeId).where({ id });
});
}
};

const down = async function (knex) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import bluebird from 'bluebird';

const TABLE_NAME = 'complementary-certification-badges';
const MESSAGE_COLUMN_NAME = 'certificateMessage';
const TEMP_MESSAGE_COLUMN_NAME = 'temporaryCertificateMessage';
Expand All @@ -19,14 +17,15 @@ const up = async function (knex) {
complementaryCertificationIds,
);

await bluebird.mapSeries(eduBadges, async ({ id, label }) => {
for (const eduBadge of eduBadges) {
const { id, label } = eduBadge;
await knex(TABLE_NAME)
.where({ id })
.update({
[MESSAGE_COLUMN_NAME]: `Vous avez obtenu la certification ${label}`,
[TEMP_MESSAGE_COLUMN_NAME]: `Vous avez obtenu le niveau “${label}” dans le cadre du volet 1 de la certification Pix+Édu. Votre niveau final sera déterminé à l’issue du volet 2`,
});
});
}
};

const down = function (knex) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import bluebird from 'bluebird';
import lodash from 'lodash';

import { PGSQL_FOREIGN_KEY_VIOLATION_ERROR } from '../../../db/pgsql-errors.js';
Expand Down Expand Up @@ -274,13 +273,13 @@ async function _sendInvitationEmails({
})
.filter((organization) => Boolean(organization.email));

await bluebird.mapSeries(createdOrganizationsWithEmail, (organizationWithEmail) =>
organizationInvitationService.createProOrganizationInvitation({
for (const organizationWithEmail of createdOrganizationsWithEmail) {
await organizationInvitationService.createProOrganizationInvitation({
organizationRepository,
organizationInvitationRepository,
...organizationWithEmail,
}),
);
});
}
} catch (error) {
_monitorError(error.message, { error, event: 'send-organizations-invitation-emails' });

Expand Down
8 changes: 3 additions & 5 deletions api/lib/domain/usecases/update-certification-center.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@
* @typedef {import('./index.js').ComplementaryCertificationHabilitationRepository} ComplementaryCertificationHabilitationRepository
* @typedef {import('./index.js').DataProtectionOfficerRepository} DataProtectionOfficerRepository
*/
import bluebird from 'bluebird';

import { CenterForAdminFactory } from '../../../src/certification/enrolment/domain/models/factories/CenterForAdminFactory.js';
import { CertificationCenterPilotFeaturesConflictError } from '../../../src/shared/domain/errors.js';
import {
Expand Down Expand Up @@ -113,13 +111,13 @@ const _updateHabilitations = async ({
await complementaryCertificationHabilitationRepository.deleteByCertificationCenterId(certificationCenterId);

if (complementaryCertificationIds) {
await bluebird.mapSeries(complementaryCertificationIds, (complementaryCertificationId) => {
for (const complementaryCertificationId of complementaryCertificationIds) {
const complementaryCertificationHabilitation = new ComplementaryCertificationHabilitation({
complementaryCertificationId: parseInt(complementaryCertificationId),
certificationCenterId,
});
return complementaryCertificationHabilitationRepository.save(complementaryCertificationHabilitation);
});
await complementaryCertificationHabilitationRepository.save(complementaryCertificationHabilitation);
}
}
};

Expand Down
6 changes: 2 additions & 4 deletions api/lib/infrastructure/events/EventBus.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import bluebird from 'bluebird';

class SubscriberList {
constructor() {
this._subscribers = new Map();
Expand Down Expand Up @@ -36,13 +34,13 @@ class EventBus {
}
async publish(event, domainTransaction) {
const subscribersToCall = this._subscriptions.get(event);
await bluebird.mapSeries(subscribersToCall, async (subscriberClass) => {
for (const subscriberClass of subscribersToCall) {
//La transaction knex est injecté dans le subscriber via le constructeur
//Du coup à chaque requête il faut re-instancier le subscriber pour passer
//une nouvelle transaction.
const subscriber = this._dependenciesBuilder.build(subscriberClass, domainTransaction);
await subscriber.handle(event);
});
}
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,24 +1,26 @@
import bluebird from 'bluebird';

import { knex } from '../../../db/knex-database-connection.js';
import { DomainTransaction } from '../DomainTransaction.js';

const BADGE_ACQUISITIONS_TABLE = 'badge-acquisitions';

const createOrUpdate = async function ({ badgeAcquisitionsToCreate = [] }) {
const knexConn = DomainTransaction.getConnection();
return bluebird.mapSeries(badgeAcquisitionsToCreate, async ({ badgeId, userId, campaignParticipationId }) => {

for (const badgeAcquisitionToCreate of badgeAcquisitionsToCreate) {
const { badgeId, userId, campaignParticipationId } = badgeAcquisitionToCreate;

const alreadyCreatedBadgeAcquisition = await knexConn(BADGE_ACQUISITIONS_TABLE)
.select('id')
.where({ badgeId, userId, campaignParticipationId });

if (alreadyCreatedBadgeAcquisition.length === 0) {
return knexConn(BADGE_ACQUISITIONS_TABLE).insert(badgeAcquisitionsToCreate);
await knexConn(BADGE_ACQUISITIONS_TABLE).insert(badgeAcquisitionsToCreate);
} else {
return knexConn(BADGE_ACQUISITIONS_TABLE)
await knexConn(BADGE_ACQUISITIONS_TABLE)
.update({ updatedAt: knex.raw('CURRENT_TIMESTAMP') })
.where({ userId, badgeId, campaignParticipationId });
}
});
}
};

const getAcquiredBadgeIds = async function ({ badgeIds, userId }) {
Expand Down
5 changes: 2 additions & 3 deletions api/scripts/add-or-update-certification-centers-dpo-infos.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import 'dotenv/config';

import * as url from 'node:url';

import bluebird from 'bluebird';
import _ from 'lodash';

import { disconnect } from '../db/knex-database-connection.js';
Expand Down Expand Up @@ -48,7 +47,7 @@ async function _updateCertificationCentersDataProtectionOfficerInformation(fileP

const dataProtectionOfficers = await parseCsvWithHeader(filePath, parsingOptions);

await bluebird.mapSeries(dataProtectionOfficers, async (dataProtectionOfficer) => {
for (const dataProtectionOfficer of dataProtectionOfficers) {
try {
await updateCertificationCenterDataProtectionOfficerInformation({
dataProtectionOfficer,
Expand All @@ -57,7 +56,7 @@ async function _updateCertificationCentersDataProtectionOfficerInformation(fileP
} catch (error) {
errors.push({ dataProtectionOfficer, error });
}
});
}

if (errors.length === 0) {
return;
Expand Down
9 changes: 4 additions & 5 deletions api/scripts/certification/send-certification-result-emails.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import 'dotenv/config';
import path from 'node:path';
import * as url from 'node:url';

import bluebird from 'bluebird';
import i18n from 'i18n';

import { disconnect } from '../../db/knex-database-connection.js';
Expand Down Expand Up @@ -39,19 +38,19 @@ async function main() {
const sessionIds = process.argv[2].split(',');
let successes = 0;

await bluebird.mapSeries(sessionIds, async (sessionId) => {
for (const sessionId of sessionIds) {
let session;

try {
session = await sharedSessionRepository.getWithCertificationCandidates({ id: parseInt(sessionId) });
} catch (e) {
logger.error({ e });
return;
continue;
}

if (!session.isPublished()) {
logger.error(`La session ${sessionId} n'est pas publiée`);
return;
continue;
}

const publishedAt = session.publishedAt;
Expand All @@ -70,7 +69,7 @@ async function main() {
} catch (e) {
logger.error(e);
}
});
}

logger.info(`Nombre de session traitées: ${successes}/${sessionIds.length}`);
logger.info('Fin du script.');
Expand Down
9 changes: 4 additions & 5 deletions api/scripts/create-badge-criteria-for-specified-badge.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { readFile } from 'node:fs/promises';
import * as url from 'node:url';

import bluebird from 'bluebird';
import Joi from 'joi';

import { disconnect } from '../db/knex-database-connection.js';
Expand Down Expand Up @@ -71,10 +70,10 @@ async function main() {
console.log('BadgeCriteria schema ok');

console.log('Saving badge criteria... ');
return DomainTransaction.execute(async () => {
await bluebird.mapSeries(jsonFile.criteria, (badgeCriterion) => {
return _createBadgeCriterion({ ...badgeCriterion, badgeId: jsonFile.badgeId });
});
await DomainTransaction.execute(async () => {
for (const badgeCriterion of jsonFile.criteria) {
await _createBadgeCriterion({ ...badgeCriterion, badgeId: jsonFile.badgeId });
}
});
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import * as url from 'node:url';

import bluebird from 'bluebird';
import _ from 'lodash';

import { disconnect, knex } from '../db/knex-database-connection.js';
import { Membership } from '../src/shared/domain/models/Membership.js';
import { PromiseUtils } from '../src/shared/infrastructure/utils/promise-utils.js';
import { parseCsvWithHeader } from './helpers/csvHelpers.js';

async function getCertificationCenterIdWithMembershipsUserIdByExternalId(externalId) {
Expand Down Expand Up @@ -60,7 +60,7 @@ async function fetchCertificationCenterMembershipsByExternalId(externalId) {

async function prepareDataForInsert(rawExternalIds) {
const externalIds = _.uniq(_.map(rawExternalIds, 'externalId'));
const certificationCenterMembershipsLists = await bluebird.mapSeries(
const certificationCenterMembershipsLists = await PromiseUtils.mapSeries(
externalIds,
fetchCertificationCenterMembershipsByExternalId,
);
Expand Down
Loading

0 comments on commit 14f7a04

Please sign in to comment.