|
| 1 | +/** |
| 2 | + * Fix the timelineTemplateIds on challenges that were wrongly updated |
| 3 | + */ |
| 4 | +global.Promise = require('bluebird') |
| 5 | + |
| 6 | +const config = require('config') |
| 7 | +const _ = require('lodash') |
| 8 | +const logger = require('../../util/logger') |
| 9 | +const { getESClient } = require('../../util/helper') |
| 10 | +const challengeService = require('../../services/challengeService') |
| 11 | + |
| 12 | +const migrationFunction = { |
| 13 | + run: async () => { |
| 14 | + const perPage = config.get('MIGRATION_SCRIPT_BATCH_SIZE') |
| 15 | + let finish = false |
| 16 | + let page = 0 |
| 17 | + let batch = 1 |
| 18 | + |
| 19 | + while (!finish) { |
| 20 | + logger.info(`Batch-${batch} - Loading challenges`) |
| 21 | + const challenges = await getChallengesMissingData(page, perPage) |
| 22 | + if (challenges.length > 0) { |
| 23 | + for (const challenge of challenges) { |
| 24 | + try { |
| 25 | + challenge.timelineTemplateId = await challengeService.mapTimelineTemplateId(challenge.trackId, challenge.typeId) |
| 26 | + await challengeService.save(challenge) |
| 27 | + } catch (e) { |
| 28 | + logger.warn(`Timeline Template Not found for trackId: ${challenge.trackId} typeId: ${challenge.typeId}`) |
| 29 | + } |
| 30 | + } |
| 31 | + } else { |
| 32 | + finish = true |
| 33 | + } |
| 34 | + page++ |
| 35 | + batch++ |
| 36 | + } |
| 37 | + } |
| 38 | +} |
| 39 | + |
| 40 | +async function getChallengesMissingData (page = 0, perPage = 10) { |
| 41 | + const esQuery = { |
| 42 | + index: config.get('ES.CHALLENGE_ES_INDEX'), |
| 43 | + type: config.get('ES.CHALLENGE_ES_TYPE'), |
| 44 | + size: perPage, |
| 45 | + from: page * perPage, |
| 46 | + body: { |
| 47 | + query: { |
| 48 | + match_all: {} |
| 49 | + } |
| 50 | + } |
| 51 | + } |
| 52 | + // logger.debug(`ES Query ${JSON.stringify(esQuery)}`) |
| 53 | + // Search with constructed query |
| 54 | + let docs |
| 55 | + try { |
| 56 | + docs = await getESClient().search(esQuery) |
| 57 | + } catch (e) { |
| 58 | + // Catch error when the ES is fresh and has no data |
| 59 | + docs = { |
| 60 | + hits: { |
| 61 | + total: 0, |
| 62 | + hits: [] |
| 63 | + } |
| 64 | + } |
| 65 | + } |
| 66 | + // Extract data from hits |
| 67 | + return _.map(docs.hits.hits, item => (item._source)) |
| 68 | +} |
| 69 | + |
| 70 | +module.exports = migrationFunction |
0 commit comments