Skip to content
Snippets Groups Projects
migration.service.ts 1.73 KiB
import { Client } from 'cozy-client'
import { Migration, MigrationResult } from './migration.type'
import { migrationLog, migrate } from './migration'
import {
  MIGRATION_RESULT_COMPLETE,
  MIGRATION_RESULT_FAILED,
} from './migration.data'
import log from 'utils/logger'
import { ReleaseNotes } from 'models/releaseNotes.model'

export class MigrationService {
  private readonly _client: Client

  constructor(_client: Client) {
    this._client = _client
  }

  async runMigrations(migrations: Migration[]): Promise<ReleaseNotes> {
    log.info('[Migration] Running migrations...')
    let releaseStatus = false
    const releaseNotes: ReleaseNotes = {
      show: releaseStatus,
      notes: [
        {
          title: '',
          description: '',
        },
      ],
    }
    for (const migration of migrations) {
      // First attempt
      const migrationResult: MigrationResult = await migrate(
        migration,
        this._client
      )
      log.info(migrationLog(migration, migrationResult))

      if (migrationResult.type === MIGRATION_RESULT_FAILED) {
        // Retry in case of failure
        const result = await migrate(migration, this._client)

        if (result.type === MIGRATION_RESULT_FAILED) {
          // Error in case of second failure
          log.error(migrationLog(migration, result))
          throw new Error()
        } else {
          log.info(migrationLog(migration, result))
        }
      }

      if (
        migration.releaseNotes !== null &&
        migrationResult.type === MIGRATION_RESULT_COMPLETE
      ) {
        releaseNotes.notes.push(migration.releaseNotes)
        releaseStatus = true
      }
    }
    releaseNotes.show = releaseStatus
    log.info('[Migration] Done')
    return releaseNotes
  }
}