|
| 1 | +import fs from 'node:fs'; |
| 2 | +import path from 'node:path'; |
| 3 | +import { Project } from 'ts-morph'; |
| 4 | + |
| 5 | +const MIGRATION_DIR = `${__dirname}/migrations`; |
| 6 | + |
| 7 | +/** |
| 8 | + * Lists all the available migrations. |
| 9 | + * |
| 10 | + * @returns {string[]} Array of migration names. |
| 11 | + */ |
| 12 | +export function listMigrations() { |
| 13 | + return fs |
| 14 | + .readdirSync(MIGRATION_DIR) |
| 15 | + .filter((fname) => fname.endsWith('.js')) |
| 16 | + .map((fname) => fname.slice(0, -3)); |
| 17 | +} |
| 18 | + |
| 19 | +/** |
| 20 | + * Runs the migration specified by name with given options. |
| 21 | + * |
| 22 | + * @param {string} name - The name of the migration. |
| 23 | + * @param {Options} options - Options for the migration. |
| 24 | + * @returns {Promise<void>} A Promise that resolves when the migration is complete. |
| 25 | + */ |
| 26 | +export default async function runMigration( |
| 27 | + name: string, |
| 28 | + options: { isVerbose?: boolean }, |
| 29 | +): Promise<void> { |
| 30 | + const { isVerbose } = options; |
| 31 | + |
| 32 | + // runMigration is called by a CLI we want the directory |
| 33 | + // the command is ran in and not the directory of this file |
| 34 | + const tsconfigPath = path.join(process.cwd(), './tsconfig.json'); |
| 35 | + if (isVerbose) { |
| 36 | + console.log(`Using the following tsconfig.json file: ${tsconfigPath}`); |
| 37 | + } |
| 38 | + const project = new Project({ |
| 39 | + tsConfigFilePath: path.join(tsconfigPath), |
| 40 | + }); |
| 41 | + |
| 42 | + const pathToMigration = path.join(MIGRATION_DIR, `${name}.js`); |
| 43 | + try { |
| 44 | + console.log(`Running the following migration: "${name}"`); |
| 45 | + const module = await import(pathToMigration); |
| 46 | + // This syntax seems odd to need when the code is packaged |
| 47 | + module.default.default(project); |
| 48 | + } catch (error) { |
| 49 | + console.error('Error importing module:', error); |
| 50 | + } |
| 51 | + |
| 52 | + await project.save(); |
| 53 | +} |
0 commit comments