var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
import { Sequelize } from "sequelize-typescript";
import { withTransaction } from "./context";
export class Connection {
    constructor(config) {
        this.newTransaction = () => __awaiter(this, void 0, void 0, function* () {
            return this.instance.transaction();
        });
        this.transactionalScope = (ctx, scope) => __awaiter(this, void 0, void 0, function* () {
            const tx = yield this.newTransaction();
            const ctxx = withTransaction(ctx, tx);
            let ret = undefined;
            try {
                ret = yield scope(ctxx)
                    .catch((error) => { throw (error); });
                yield tx.commit();
            }
            catch (error) {
                yield tx.rollback();
                return Promise.reject(error);
            }
            return ret;
        });
        this.repositories = new Map;
        this.instance = {};
        this.releaseFn = config.releaseFn;
        try {
            this.instance = new Sequelize(Object.assign(Object.assign({}, config.options), { database: config.databaseName, username: config.credentials.username, password: config.credentials.password, schema: config.schema, port: parseInt(config.credentials.port), host: config.credentials.host, dialect: config.credentials.engine, models: config.models }));
        }
        catch (e) {
            console.log(e);
        }
    }
    getRepository(model) {
        return __awaiter(this, void 0, void 0, function* () {
            return this.instance.getRepository(model);
        });
    }
    release() {
        if (this.releaseFn) {
            this.releaseFn();
        }
    }
    close() {
        this.instance.close();
    }
    migrate() {
        // Add ".sync()" to create the tables
        return this.instance.sync({
            alter: true,
            force: true
        });
    }
}
//# sourceMappingURL=connection.js.map