Last active
October 19, 2023 07:15
-
-
Save lljxx1/9631a42ecacb82dbe78e861a098750a2 to your computer and use it in GitHub Desktop.
Convert node-pg-migrate migrations file to TypeORM style migration
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fs = require("fs"); | |
const camelcase = require("camelcase"); | |
const baseDir = "src/migrations"; | |
const outputDir = "src/migration"; | |
const allFiles = fs.readdirSync(baseDir); | |
for (let index = 0; index < allFiles.length; index++) { | |
const filename = allFiles[index]; | |
const [timestamp, migrationFileName] = filename.split("_"); | |
const [migrationNameRaw] = migrationFileName.split("."); | |
const migrationName = camelcase(migrationNameRaw, { | |
pascalCase: true, | |
}); | |
const content = fs.readFileSync(`${baseDir}/${filename}`, "utf-8"); | |
const [up, down] = content.split("-- Down Migration"); | |
const downSql = cleanComment(down.trim()); | |
const upSql = cleanComment(up.replace("-- Up Migration", "")); | |
function cleanComment(code) { | |
return code.split("\n").filter(c => !c.includes("--")).map(c => c.replace("'\\x", "'\\\\x")).join("\n"); | |
} | |
const typeormMig = ` | |
import { MigrationInterface, QueryRunner } from "typeorm" | |
export class ${migrationName}${timestamp} implements MigrationInterface { | |
${upSql ? | |
` | |
async up(queryRunner: QueryRunner): Promise<void> { | |
await queryRunner.query( | |
\`${upSql}\` | |
) | |
} | |
` : ` | |
async up(): Promise<void> { | |
// Empty | |
} | |
`} | |
${downSql ? | |
` | |
async down(queryRunner: QueryRunner): Promise<void> { | |
await queryRunner.query( | |
\`${downSql}\` | |
) | |
} | |
` : ` | |
async down(): Promise<void> { | |
// Empty | |
} | |
`} | |
}`; | |
fs.writeFileSync(`${outputDir}/${timestamp}-${migrationName}.ts`, typeormMig); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment