Replies: 2 comments
-
Wrote external script (focus on import { spawnSync } from 'child_process';
import fs, { readFileSync, writeFileSync } from 'fs';
import { join } from 'path';
import { Sequelize, SequelizeOptions } from 'sequelize-typescript';
import { SequelizeTypescriptMigration } from 'sequelize-typescript-migration-lts';
import configs from '@/db/db.config';
import { getModels } from '@/db/models';
const ENV = process.env.NODE_ENV || 'development';
const DB_CONFIG = (configs as Record<string, SequelizeOptions>)[ENV];
const MIGRATION_NAME = 'create-tables-from-models-code';
console.log(DB_CONFIG);
const migrationsGeneratedPath = join(__dirname, '../src/db/migrations.generated');
function createFolder(folderPath: string) {
if (!fs.existsSync(folderPath)) {
fs.mkdirSync(folderPath);
}
}
const simplifyForeignKeysDeclaration = (code: string) => {
code = code.replaceAll(/([ \t]*)"references": \{[\s\n\r]+"model": (\{[^\}]*\})/gm, (substring, padding, matched) => {
let result = substring;
try {
let referenceInfo = JSON.parse(matched);
const { schema, tableName } = referenceInfo;
delete referenceInfo['table'];
if (schema === 'public') {
referenceInfo = tableName;
}
result = `${padding}"references": {\n` + `${padding} "model": ${JSON.stringify(referenceInfo, null, ' ')}`;
} catch (e) {
console.error(e);
}
return result;
});
return code;
};
const asyncMain = async () => {
createFolder(migrationsGeneratedPath);
const sequelize: Sequelize = new Sequelize({
...DB_CONFIG,
models: getModels(),
});
try {
const fnLogOriginal = console.log;
let filePath: string | null = null;
console.log = (...args: any[]) => {
const firstArg = args[0];
if (typeof firstArg === 'string' && firstArg.match(/^New migration to revision/)) {
const fileNameMatch = firstArg.match(/'([^']*)'/);
if (fileNameMatch && fileNameMatch[1]) {
filePath = fileNameMatch[1];
}
}
return fnLogOriginal(...args);
};
const result = await SequelizeTypescriptMigration.makeMigration(sequelize, {
outDir: migrationsGeneratedPath,
migrationName: MIGRATION_NAME,
useSnakeCase: true,
});
console.log = fnLogOriginal;
console.log('result:', result);
console.log('filePath', filePath);
if (!filePath) {
throw new Error("can't detect file path of new migration");
}
let code = readFileSync(filePath, { encoding: 'utf8' });
console.log('Simplifying foreign keys declaration');
code = simplifyForeignKeysDeclaration(code);
writeFileSync(filePath, code);
// to reformat code after changes properly
const prettierCommand = `npm exec prettier -- --write ${filePath}`;
console.log('Running prettier on migration file:');
spawnSync(prettierCommand, { stdio: 'inherit', shell: true });
} catch (e) {
console.log(e);
}
};
asyncMain(); |
Beta Was this translation helpful? Give feedback.
0 replies
-
Can you at least also return |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
instead of
See sequelize/src/model.d.ts at v6.37.1 · sequelize/sequelize:
Beta Was this translation helpful? Give feedback.
All reactions