|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +const { v4 } = require('uuid'); |
| 4 | + |
| 5 | +const LIMIT_LABEL = 'mail-access'; |
| 6 | + |
| 7 | +/** @type {import('sequelize-cli').Migration} */ |
| 8 | +module.exports = { |
| 9 | + async up(queryInterface) { |
| 10 | + const transaction = await queryInterface.sequelize.transaction(); |
| 11 | + try { |
| 12 | + const disabledLimitId = v4(); |
| 13 | + const enabledLimitId = v4(); |
| 14 | + |
| 15 | + await queryInterface.bulkInsert( |
| 16 | + 'limits', |
| 17 | + [ |
| 18 | + { |
| 19 | + id: disabledLimitId, |
| 20 | + label: LIMIT_LABEL, |
| 21 | + type: 'boolean', |
| 22 | + value: 'false', |
| 23 | + created_at: new Date(), |
| 24 | + updated_at: new Date(), |
| 25 | + }, |
| 26 | + { |
| 27 | + id: enabledLimitId, |
| 28 | + label: LIMIT_LABEL, |
| 29 | + type: 'boolean', |
| 30 | + value: 'true', |
| 31 | + created_at: new Date(), |
| 32 | + updated_at: new Date(), |
| 33 | + }, |
| 34 | + ], |
| 35 | + { transaction }, |
| 36 | + ); |
| 37 | + |
| 38 | + const [tiers] = await queryInterface.sequelize.query( |
| 39 | + `SELECT id, label FROM tiers`, |
| 40 | + { transaction }, |
| 41 | + ); |
| 42 | + |
| 43 | + const tierLimitRelations = tiers.map((tier) => ({ |
| 44 | + id: v4(), |
| 45 | + tier_id: tier.id, |
| 46 | + limit_id: disabledLimitId, |
| 47 | + created_at: new Date(), |
| 48 | + updated_at: new Date(), |
| 49 | + })); |
| 50 | + |
| 51 | + await queryInterface.bulkInsert('tiers_limits', tierLimitRelations, { |
| 52 | + transaction, |
| 53 | + }); |
| 54 | + |
| 55 | + await transaction.commit(); |
| 56 | + } catch (error) { |
| 57 | + await transaction.rollback(); |
| 58 | + throw error; |
| 59 | + } |
| 60 | + }, |
| 61 | + |
| 62 | + async down(queryInterface) { |
| 63 | + const transaction = await queryInterface.sequelize.transaction(); |
| 64 | + try { |
| 65 | + const [limits] = await queryInterface.sequelize.query( |
| 66 | + `SELECT id FROM limits WHERE label = :limitLabel`, |
| 67 | + { replacements: { limitLabel: LIMIT_LABEL }, transaction }, |
| 68 | + ); |
| 69 | + |
| 70 | + const limitIds = limits.map((l) => l.id); |
| 71 | + |
| 72 | + if (limitIds.length > 0) { |
| 73 | + await queryInterface.sequelize.query( |
| 74 | + `DELETE FROM tiers_limits WHERE limit_id IN (:limitIds)`, |
| 75 | + { replacements: { limitIds }, transaction }, |
| 76 | + ); |
| 77 | + } |
| 78 | + |
| 79 | + await queryInterface.sequelize.query( |
| 80 | + `DELETE FROM limits WHERE label = :limitLabel`, |
| 81 | + { replacements: { limitLabel: LIMIT_LABEL }, transaction }, |
| 82 | + ); |
| 83 | + |
| 84 | + await transaction.commit(); |
| 85 | + } catch (error) { |
| 86 | + await transaction.rollback(); |
| 87 | + throw error; |
| 88 | + } |
| 89 | + }, |
| 90 | +}; |
0 commit comments