translate-table
Version:
A powerful CLI tool for translating PostgreSQL table content to multiple languages and generating translations for internationalization (i18n).
73 lines • 2.96 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateFiles = generateFiles;
const node_fs_1 = __importDefault(require("node:fs"));
const node_path_1 = __importDefault(require("node:path"));
const consola_1 = __importDefault(require("consola"));
/**
* Generates SQL INSERT statement for translations
*
* @param tableName - Table name for insertion
* @param values - Translation values to be inserted
* @returns String containing SQL INSERT statement
*/
function generateInsert(tableName, values) {
// Escape strings to prevent SQL injection
const escapeSQL = (text) => {
if (!text)
return "";
return text.replace(/'/g, "''");
};
// Create value clauses for each translation
const inserts = values.map((value) => {
return `(${value.itemId}, '${escapeSQL(value.language)}', '${escapeSQL(value.text)}')`;
});
return `INSERT INTO ${tableName} (item_id, "language", "text") VALUES ${inserts.join(", ")};`;
}
/**
* Generates SQL files for table creation and translation insertion
*
* @param tableName - Base table name
* @param values - Translated values to be inserted
*/
function generateFiles(tableName, values) {
consola_1.default.info("Generating SQL files...");
// Table name for translations
const translationsTable = `${tableName}_translations`;
// Generate SQL for insertion
const rawInsertSQL = generateInsert(translationsTable, values);
// Generate SQL for table creation
const createTableSQL = `
CREATE TABLE IF NOT EXISTS ${translationsTable} (
id SERIAL PRIMARY KEY,
item_id INT NOT NULL REFERENCES ${tableName} (id),
"language" VARCHAR(10) NOT NULL,
"text" TEXT NOT NULL
)`;
// Output filename
const sqlFileName = `${translationsTable}.sql`;
// Split SQL instructions into lines for better readability
const insertLines = rawInsertSQL.match(/.{1,400}/g) || [];
const formattedInsertSQL = insertLines.join("\n");
// Combine creation and insertion SQL
const sqlFileContent = `${createTableSQL}\n\n${formattedInsertSQL}`;
const sqlDirPath = "./sql";
const sqlFilePath = node_path_1.default.join(sqlDirPath, sqlFileName);
try {
// Ensure directory exists
if (!node_fs_1.default.existsSync(sqlDirPath)) {
node_fs_1.default.mkdirSync(sqlDirPath, { recursive: true });
}
// Write SQL file
node_fs_1.default.writeFileSync(sqlFilePath, sqlFileContent, "utf8");
consola_1.default.success(`SQL file ${sqlFileName} generated successfully!`);
}
catch (error) {
consola_1.default.error(`Error generating SQL file: ${error.message}`);
throw new Error(`Failed to create SQL file: ${error.message}`);
}
}
//# sourceMappingURL=sql.js.map