const axios = require("axios") const { MongoClient } = require("mongodb") const fs = require("fs") const util = require("util") // Function to log objects in a detailed manner function logObj(o) { console.log(util.inspect(o, false, null, true)) } // Function to preload the database with collections async function preloadDatabase(db, collections) { for (const { name, file } of collections) { const content = fs.readFileSync(file, "utf8") const data = JSON.parse(content) const collection = db.collection(name) await collection.insertMany(data) const insertedData = await collection.find({}).toArray() if (insertedData.length !== data.length) { console.error( `Mismatch in collection ${name}: expected ${data.length} documents, found ${insertedData.length}` ) } else { console.log(`Successfully verified ${insertedData.length} documents in ${name}`) } } } async function initializeDatabase(config) { try { const dbClient = new MongoClient(config.mongodbUri) await dbClient.connect() let db = dbClient.db(config.tibiDbPrefix) await db.collection("project").deleteMany({ namespace: config.projectApiNamespace }) const dbName = config.tibiDbPrefix + "_" + config.projectApiNamespace db = dbClient.db(dbName) await db.dropDatabase() // Login to Tibi API const loginResponse = await axios.post(config.tibiApiUrl + "/login", { username: config.tibiUsername, password: config.tibiPassword, }) const tibiToken = loginResponse.data.token // Create project let project try { const projectResponse = await axios.post( config.tibiApiUrl + "/project", { configFile: config.projectApiConfig, name: config.projectApiNamespace, namespace: config.projectApiNamespace, description: config.projectApiNamespace, }, { headers: { "X-Auth-Token": tibiToken, }, } ) project = projectResponse.data } catch (e) { logObj(e) throw e } // Check if project is online const projectStatus = await axios.get(config.tibiApiUrl + "/project/" + project.id, { headers: { "X-Auth-Token": tibiToken, }, }) if (!projectStatus.data.api.isOnline) { throw new Error(`Project ${config.projectApiNamespace} is not online.`) } // Define collections to preload into the database const collections = [ // Define your collections here as per your Cypress plugin logic // { name: "collectionName", file: "path/to/file.json" }, // ... other collections ] await preloadDatabase(db, collections) await dbClient.close() } catch (error) { console.error("Error initializing the database:", error) throw error } } // Run the script if it's executed directly if (require.main === module) { const config = { projectApiNamespace: process.env.PROJECT_API_NAMESPACE, mongodbUri: process.env.MONGODB_URI, tibiDbPrefix: process.env.TIBI_DB_PREFIX, tibiApiUrl: process.env.TIBI_API_URL, // Add other required environment variables here } initializeDatabase(config) .then(() => console.log("Database initialized successfully")) .catch((err) => { console.error("Failed to initialize database:", err) process.exit(1) }) } module.exports = initializeDatabase