oak-backend-base/lib/utils/dbPriority.js

56 lines
2.3 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getDbStoreClass = exports.getDbConfig = exports.DbTypeSymbol = exports.dbList = void 0;
const oak_db_1 = require("oak-db");
const path_1 = require("path");
const fs_1 = require("fs");
/**
* 数据库优先级列表,按顺序尝试获取配置文件
*/
exports.dbList = {
mysql: oak_db_1.MysqlStore,
postgres: oak_db_1.PostgreSQLStore
};
exports.DbTypeSymbol = Symbol.for('oak:backend:db:type');
const getDbConfig = (path) => {
for (const db of Object.keys(exports.dbList)) {
try {
// eslint-disable-next-line @typescript-eslint/no-var-requires
let dbConfigFile = (0, path_1.join)(path, 'configuration', `${db}.${process.env.NODE_ENV}.json`);
if ((0, fs_1.existsSync)(dbConfigFile) === false) {
dbConfigFile = (0, path_1.join)(path, 'configuration', `${db}.json`);
}
if ((0, fs_1.existsSync)(dbConfigFile) === false) {
continue;
}
const config = require(dbConfigFile);
console.log(`使用${db}作为数据库`);
// 定义不可枚举的属性,避免被序列化
Object.defineProperty(config, exports.DbTypeSymbol, {
value: db,
enumerable: false,
writable: false,
configurable: false
});
return config;
}
catch (err) {
// do nothing
}
}
throw new Error(`没有找到数据库配置文件请在configuration目录下添加任一配置文件${Object.keys(exports.dbList).map(ele => `${ele}.json`).join('、')}`);
};
exports.getDbConfig = getDbConfig;
const getDbStoreClass = (config) => {
const dbType = Object.getOwnPropertyDescriptor(config, exports.DbTypeSymbol)?.value;
if (!dbType) {
throw new Error('无法获取数据库类型,请确认是否存在数据库配置文件');
}
const DbStoreClass = exports.dbList[dbType.toLowerCase()];
if (!DbStoreClass) {
throw new Error(`不支持的数据库类型:${dbType},请确认是否存在以下配置文件:${Object.keys(exports.dbList).map(ele => `${ele}.json`).join('、')}`);
}
return DbStoreClass;
};
exports.getDbStoreClass = getDbStoreClass;