|
| 1 | +import * as dotenv from "dotenv"; |
| 2 | +dotenv.config(); |
| 3 | + |
| 4 | +import { Client } from "pg"; |
| 5 | + |
| 6 | +// Set up the PostgreSQL client with your configuration |
| 7 | +const client = new Client({ |
| 8 | + connectionString: process.env.POSTGRES_URL, |
| 9 | +}); |
| 10 | + |
| 11 | +async function createTableIfNotExist(client, tableName) { |
| 12 | + const createTableQuery = ` |
| 13 | + CREATE TABLE IF NOT EXISTS ${tableName} ( |
| 14 | + id SERIAL PRIMARY KEY, |
| 15 | + json_data JSONB NOT NULL |
| 16 | + ); |
| 17 | + `; |
| 18 | + await client.query(createTableQuery); |
| 19 | + console.log(`Table ${tableName} is ready, or already exists.`); |
| 20 | +} |
| 21 | + |
| 22 | +async function truncateTable(client, tableName) { |
| 23 | + const truncateQuery = `TRUNCATE TABLE ${tableName};`; |
| 24 | + await client.query(truncateQuery); |
| 25 | + console.log(`Truncated table ${tableName}`); |
| 26 | +} |
| 27 | + |
| 28 | +async function uploadJsonDataFromFile(client, relativePath, tableName) { |
| 29 | + try { |
| 30 | + const module = await import(`../${relativePath}`); |
| 31 | + const jsonDataFromFile = module.default; |
| 32 | + |
| 33 | + await createTableIfNotExist(client, tableName); |
| 34 | + await truncateTable(client, tableName); |
| 35 | + |
| 36 | + // Assuming jsonDataFromFile is an array of objects |
| 37 | + for (const data of jsonDataFromFile) { |
| 38 | + const query = { |
| 39 | + text: `INSERT INTO ${tableName}(json_data) VALUES(\$1)`, |
| 40 | + values: [JSON.stringify(data)], // Convert data to JSON string |
| 41 | + }; |
| 42 | + await client.query(query); |
| 43 | + } |
| 44 | + |
| 45 | + console.log(`Data from ${relativePath} inserted successfully into ${tableName}`); |
| 46 | + } catch (err) { |
| 47 | + console.error(`Error uploading data from file ${relativePath}:`, err); |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +async function uploadAllFiles(client) { |
| 52 | + const files = ["books.js", "feeds.js", "movies.js", "music.js", "musicals.js", "prompts.js", "series.js", "words.js"]; |
| 53 | + |
| 54 | + for (const file of files) { |
| 55 | + const tableName = file.replace('.js', ''); // Remove '.js' to form the table name |
| 56 | + await uploadJsonDataFromFile(client, `data/${file}`, tableName); |
| 57 | + } |
| 58 | +} |
| 59 | + |
| 60 | +async function main() { |
| 61 | + try { |
| 62 | + await client.connect(); |
| 63 | + await uploadAllFiles(client); |
| 64 | + console.log("Data uploaded successfully"); |
| 65 | + } catch (err) { |
| 66 | + console.error("Error uploading data:", err); |
| 67 | + } finally { |
| 68 | + await client.end(); |
| 69 | + console.log("Disconnected from the database."); |
| 70 | + } |
| 71 | +} |
| 72 | +main(); |
0 commit comments