UNPKG

translate-table

Version:

A powerful CLI tool for translating PostgreSQL table content to multiple languages and generating translations for internationalization (i18n).

95 lines 3.1 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.getTableAndValues = getTableAndValues; exports.insertIntoDatabase = insertIntoDatabase; const consola_1 = __importDefault(require("consola")); const postgres_1 = __importDefault(require("postgres")); /** * Creates a database connection * @returns A Postgres connection instance */ function createDbConnection(url) { if (!url) { throw new Error("DATABASE_URL not defined in environment variables"); } return (0, postgres_1.default)(url); } /** * Fetches all records from a specific table * * @param tableName - Name of the table to query * @returns Promise with array of results */ async function getTableAndValues(url, tableName) { if (!tableName) { throw new Error("Table name is required"); } const sql = createDbConnection(url); try { // SQL query with safe table name via sql tagged template const items = await sql ` SELECT id, name FROM ${sql(tableName)} ORDER BY id `; return items; } catch (error) { consola_1.default.error("Error fetching data from database:", error); throw new Error(`Failed to fetch data from database: ${error.message}`); } finally { // Close connection await sql.end(); } } /** * Inserts translations into the database * * @param tableName - Base table name * @param values - Translations to be inserted */ async function insertIntoDatabase(url, tableName, values) { if (!tableName) { throw new Error("Table name is required"); } if (!values.length) { consola_1.default.warn("No values to insert into database"); return; } const sql = createDbConnection(url); const newTableName = `${tableName}_translations`; try { // Use transaction to ensure all operations are atomic const rows = await sql.begin(async (transaction) => { // Create table if it doesn't exist await transaction ` CREATE TABLE IF NOT EXISTS ${transaction(newTableName)} ( id SERIAL PRIMARY KEY, item_id INTEGER NOT NULL REFERENCES ${transaction(tableName)}(id), "language" TEXT NOT NULL, "text" TEXT NOT NULL ) `; // Insert all values at once const insertedRows = await transaction ` INSERT INTO ${transaction(newTableName)} ${transaction(values.map((v) => ({ item_id: v.itemId, language: v.language, text: v.text })))} RETURNING * `; return insertedRows; }); consola_1.default.success(`Inserted ${rows.length} rows into ${newTableName}`); } catch (error) { consola_1.default.error("Error inserting data into database:", error); throw new Error(`Failed to insert data into database: ${error.message}`); } finally { // Always close the connection await sql.end(); } } //# sourceMappingURL=db.js.map