{"size": 1258, "ext": "js", "max_stars_repo_path": "utils/mongo.js", "max_stars_repo_name": "samuelko123/book-store-api", "max_stars_repo_stars_event_min_datetime": "2022-01-03T02:16:34.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-03T02:16:34.000Z", "max_issues_repo_path": "utils/mongo.js", "max_issues_repo_name": "samuelko123/book-store-api", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "utils/mongo.js", "max_forks_repo_name": "samuelko123/book-store-api", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 1, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 27.9555555556, "max_line_length": 89, "alphanum_fraction": 0.5651828299}
const MongoClient = require('mongodb').MongoClient
const logger = require('./logger')

module.exports = new function () {
    this.client = null
    this.db = null

    this.connect = async function (uri) {
        this.client = await MongoClient.connect(uri, {
            useNewUrlParser: true,
            useUnifiedTopology: true,
        })
        this.db = this.client.db()

        await this.create_collections()
        await this.set_indexes()

        logger.info('Connected to database')
    }

    this.create_collections = async function () {
        let coll_names = await this.db.listCollections().toArray()
        coll_names = coll_names.map(x => x.name)

        const models = require('../models')
        for (let key in models) {
            let model = models[key]

            if (!coll_names.includes(model.name)) {
                await this.db.createCollection(model.name)
            }
        }
    }

    this.set_indexes = async function () {
        const models = require('../models')
        for (let key in models) {
            let model = models[key]

            for (let field of model.indexes) {
                await this.db.collection(model.name).createIndex(field, { unique: true })
            }
        }
    }
}