budibase/scripts/add-app-migration.js

83 lines
2.3 KiB
JavaScript
Raw Normal View History

2023-11-27 12:25:48 +01:00
const fs = require("fs")
const path = require("path")
2023-12-05 11:02:44 +01:00
const argv = require("yargs").demandOption(
["title"],
"Please provide the required parameter: --title=[title]"
).argv
const { title } = argv
2023-11-27 12:25:48 +01:00
const generateTimestamp = () => {
const now = new Date()
const year = now.getFullYear()
const month = String(now.getMonth() + 1).padStart(2, "0")
const day = String(now.getDate()).padStart(2, "0")
const hours = String(now.getHours()).padStart(2, "0")
const minutes = String(now.getMinutes()).padStart(2, "0")
const seconds = String(now.getSeconds()).padStart(2, "0")
return `${year}${month}${day}${hours}${minutes}${seconds}`
}
const createMigrationFile = () => {
2023-12-29 12:25:25 +01:00
const migrationFilename = `${generateTimestamp()}_${title
.replace(/-/g, "_")
.replace(/ /g, "_")}`
2023-11-27 12:25:48 +01:00
const migrationsDir = "../packages/server/src/appMigrations"
const template = `const migration = async () => {
// Add your migration logic here
}
export default migration
`
const newMigrationPath = path.join(
migrationsDir,
"migrations",
2023-12-05 11:02:44 +01:00
`${migrationFilename}.ts`
2023-11-27 12:25:48 +01:00
)
fs.writeFileSync(path.resolve(__dirname, newMigrationPath), template)
console.log(`New migration created: ${newMigrationPath}`)
// Append the new migration to the main migrations file
const migrationsFilePath = path.join(migrationsDir, "migrations.ts")
const migrationDir = fs.readdirSync(
path.join(__dirname, migrationsDir, "migrations")
)
const migrations = migrationDir
.filter(m => m.endsWith(".ts"))
.map(m => m.substring(0, m.length - 3))
let migrationFileContent =
2023-12-05 15:31:32 +01:00
'// This file should never be manually modified, use `yarn add-app-migration` in order to add a new one\n\nimport { AppMigration } from "."\n\n'
2023-11-27 12:25:48 +01:00
for (const migration of migrations) {
migrationFileContent += `import m${migration} from "./migrations/${migration}"\n`
}
2023-12-05 15:31:32 +01:00
migrationFileContent += `\nexport const MIGRATIONS: AppMigration[] = [
// Migrations will be executed sorted by id\n`
2023-11-27 12:25:48 +01:00
for (const migration of migrations) {
2023-11-29 13:28:52 +01:00
migrationFileContent += ` {
2023-12-05 15:31:32 +01:00
id: "${migration}",
func: m${migration}
2023-11-29 13:28:52 +01:00
},\n`
2023-11-27 12:25:48 +01:00
}
2023-11-29 13:28:52 +01:00
migrationFileContent += `]\n`
2023-11-27 12:25:48 +01:00
fs.writeFileSync(
path.resolve(__dirname, migrationsFilePath),
migrationFileContent
)
console.log(`Main migrations file updated: ${migrationsFilePath}`)
}
createMigrationFile()