@fdm-monster/server
Version:
FDM Monster is a bulk OctoPrint, Klipper, PrusaLink and BambuLab manager to set up, configure and monitor 3D printers. Our aim is to provide neat overview over your farm.
128 lines (123 loc) • 4.5 kB
JavaScript
import path from "node:path";
import * as readline from "node:readline";
import { CommandUtils } from "typeorm/commands/CommandUtils";
import chalk from "chalk";
import { camelCase } from "typeorm/util/StringUtils";
import { PlatformTools } from "typeorm/platform/PlatformTools";
import { format } from "@sqltools/formatter/lib/sqlFormatter.js";
//#region src/consoles/typeorm-generate.ts
/**
* Formats query parameters for migration queries if parameters actually exist
*/
function queryParams(parameters) {
if (!parameters || !parameters.length) return "";
return `, ${JSON.stringify(parameters)}`;
}
/**
* Gets contents of the migration file.
*/
function getTemplate(name, timestamp, upSqls, downSqls) {
const migrationName = `${camelCase(name, true)}${timestamp}`;
return `import { MigrationInterface, QueryRunner } from "typeorm";
export class ${migrationName} implements MigrationInterface {
name = '${migrationName}'
public async up(queryRunner: QueryRunner): Promise<void> {
${upSqls.join(`
`)}
}
public async down(queryRunner: QueryRunner): Promise<void> {
${downSqls.join(`
`)}
}
}
`;
}
/**
*
*/
function prettifyQuery(query) {
return "\n" + format(query, { indent: " " }).replace(/^/gm, " ") + "\n ";
}
async function confirm(question, hint) {
const line = readline.createInterface({
input: process.stdin,
output: process.stdout
});
return new Promise((resolve) => {
line.question(question, (response) => {
line.close();
resolve(response);
});
line.write(hint);
});
}
async function main() {
const timestamp = CommandUtils.getTimestamp(Date.now());
const extension = ".ts";
let dataSource = void 0;
try {
dataSource = await CommandUtils.loadDataSource(path.resolve(process.cwd(), "dist/data-source.js"));
dataSource.setOptions({
synchronize: false,
migrationsRun: false,
dropSchema: false,
logging: false
});
await dataSource.initialize();
const hasPendingMigrations = await dataSource.showMigrations();
if (hasPendingMigrations) {
console.log(chalk.yellow(`ATTENTION: you have pending migrations (${chalk.blue(hasPendingMigrations)}). Running those first, before generating a new migration.`));
await dataSource.runMigrations({ transaction: "each" });
console.log(chalk.green(`Migrations successfully executed.`));
}
const upSqls = [], downSqls = [];
try {
const sqlInMemory = await dataSource.driver.createSchemaBuilder().log();
sqlInMemory.upQueries.forEach((upQuery) => {
upQuery.query = prettifyQuery(upQuery.query);
});
sqlInMemory.downQueries.forEach((downQuery) => {
downQuery.query = prettifyQuery(downQuery.query);
});
sqlInMemory.upQueries.forEach((upQuery) => {
upSqls.push(" await queryRunner.query(`" + upQuery.query.replace(/* @__PURE__ */ new RegExp("`", "g"), "\\`") + "`" + queryParams(upQuery.parameters) + ");");
});
sqlInMemory.downQueries.forEach((downQuery) => {
downSqls.push(" await queryRunner.query(`" + downQuery.query.replace(/* @__PURE__ */ new RegExp("`", "g"), "\\`") + "`" + queryParams(downQuery.parameters) + ");");
});
} finally {
await dataSource.destroy();
}
if (!upSqls.length) {
console.log(chalk.green(`No changes in database schema were found`));
process.exit(0);
}
console.log(chalk.green(`Migration ready to be saved...`));
console.log(chalk.blue(upSqls.map((s) => s).join("\n")));
let name;
while (!name) {
name = (await confirm("Please provide a name for the migration: ", "Change"))?.trim();
if (name) break;
console.log(chalk.red(`Name is required, try again`));
process.exit(1);
}
const fullPath = path.resolve(process.cwd(), `src/migrations/${name}`);
const filename = timestamp + "-" + path.basename(fullPath) + extension;
const fileContent = getTemplate(path.basename(fullPath), timestamp, upSqls, downSqls.reverse());
const migrationFileName = path.dirname(fullPath) + "/" + filename;
await CommandUtils.createFile(migrationFileName, fileContent);
console.log(chalk.green(`Migration ${chalk.blue(migrationFileName)} has been generated successfully.`));
} catch (err) {
PlatformTools.logCmdErr("Error during migration generation:", err);
process.exit(1);
}
}
let start = (/* @__PURE__ */ new Date()).getTime();
main().then(() => {
let end = (/* @__PURE__ */ new Date()).getTime();
console.log("done", end - start, "ms");
process.exit(0);
});
//#endregion
export {};
//# sourceMappingURL=typeorm-generate.js.map