0
Fork 0
mirror of https://github.com/TryGhost/Ghost.git synced 2025-03-11 02:12:21 -05:00

Truncated offers.name to 40 characters (#13781)

refs https://github.com/TryGhost/Team/issues/1236

We use Offer names for the Stripe Coupon name - which has a limit of 40
characters. We are now introducing a limit of 40 characters to Offer
names too. This migration ensures that all our data in the DB is valid.
This commit is contained in:
Fabien 'egg' O'Carroll 2021-11-25 12:33:22 +02:00 committed by Daniel Lockyer
parent 15d5905549
commit 483ba3e0f9
No known key found for this signature in database
GPG key ID: D21186F0B47295AD

View file

@ -0,0 +1,58 @@
const logging = require('@tryghost/logging');
const {createTransactionalMigration} = require('../../utils');
/**
* @param {(val: string) => boolean} exists
* @param {string} requested
* @param {string} attempt
* @param {number} n
*
* @returns {string}
*/
function getUnique(exists, requested, attempt = requested, n = 1) {
if (!exists(attempt)) {
return attempt;
}
const newAttempt = requested.slice(0, -n.toString().length) + n;
return getUnique(exists, requested, newAttempt, n + 1);
}
module.exports = createTransactionalMigration(
async function up(knex) {
const allOffers = await knex
.select('id', 'name')
.from('offers');
const offersNeedingTrunctation = allOffers.filter((row) => {
return row.name.length >= 40;
});
if (offersNeedingTrunctation.length === 0) {
logging.warn('No Offers found needing truncation');
return;
} else {
logging.info(`Found ${offersNeedingTrunctation.length} Offers needing truncation`);
}
const truncatedOffers = offersNeedingTrunctation.reduce((offers, row) => {
function exists(name) {
return offers.find(offer => offer.name === name) !== undefined;
}
const updatedRow = {
id: row.id,
name: getUnique(exists, row.name.slice(0, 40))
};
return offers.concat(updatedRow);
}, []);
for (const truncatedOffer of truncatedOffers) {
await knex('offers')
.update('name', truncatedOffer.name)
.where('id', truncatedOffer.id);
}
},
// no-op we've lost the data required to roll this back
async function down() {}
);