restful-started
Version:
typescript restful started
59 lines (58 loc) • 2.36 kB
JavaScript
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
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) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const sequelize_1 = require("sequelize");
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
class DB {
constructor() {
this.isConfig = false;
}
config(options) {
this.db = new sequelize_1.Sequelize(options.url);
this.isConfig = true;
}
dbInit() {
return __awaiter(this, void 0, void 0, function* () {
if (!this.isConfig) {
return;
}
if (!this.db) {
throw new Error("need call config before!");
}
let finalOptions = Object.assign(exports.DEFAULT_DATABASE_OPTIONS, this._options);
let files = fs.readdirSync(finalOptions.modelDir);
for (let f of files) {
if (!/\.map\.js/.test(f) && !/\.d\.ts/.test(f) && !/^_\w/.test(f)) {
let model = require(path.resolve(finalOptions.modelDir, f));
if (model.init && typeof model.init == 'function') {
console.debug("init ", f);
yield model.init(this.db);
}
}
}
return this.db.sync({ force: finalOptions.force });
});
}
}
exports.DB = DB;
exports.DEFAULT_DATABASE_OPTIONS = {
modelDir: path.join(process.cwd(), 'model'),
force: false,
};
const db = new DB();
exports.default = db;
;