cooperation
Version:
42 lines (37 loc) • 1.29 kB
JavaScript
const path = require('path');
const fs = require('fs-extra');
const low = require('lowdb');
const FileAsync = require('lowdb/adapters/FileAsync');
const Cryptr = require("cryptr");
const log = require('cooperation/util/log');
const cryptr = new Cryptr('Zoolon');
const NAME = path.basename(__filename, '.js');
const dbStory = new Map();
function conn({dev = false, dbs = []} = {}) {
dbs.forEach(v => {
let name = path.basename(v, '.db');
if (dbStory.has(name)) {
log("名为" + name + "数据库链接已建立", "WARN");
return;
}
try {
//自动初始化
fs.ensureFileSync(v);
//获取加密连接
let cryptrImpl = dev ? {} : {
//实现加密接口
serialize: data => cryptr.encrypt(JSON.stringify(data)),
//实现解密接口
deserialize: data => JSON.parse(cryptr.decrypt(data))
};
low(new FileAsync(v, cryptrImpl)).then(db => dbStory.set(name, db));
console.log(NAME + ":使用了 " + v + " 数据库文件");
} catch (e) {
log("数据库连接异常!", "ERROR");
}
});
}
module.exports = {
conn,
use: name => dbStory.get(name)
};