129 lines
2.6 KiB
JavaScript
129 lines
2.6 KiB
JavaScript
const utils = require('j7/utils');
|
|
const app = require('j7/app');
|
|
const error = require('j7/error');
|
|
const modelsFactory = require('./models/factory');
|
|
const serviceFactory = require('./services/factory');
|
|
const metaFactory = require('./metadata/factory');
|
|
|
|
class Session {
|
|
|
|
constructor(req, rsp) {
|
|
this.req = req;
|
|
this.rsp = rsp;
|
|
this.nowTime = utils.getUtcTime();
|
|
this.useConns = {};
|
|
}
|
|
|
|
async destory() {
|
|
if (this.user) {
|
|
await this.user.destory();
|
|
}
|
|
for (let key in this.useConns) {
|
|
this.useConns[key].release();
|
|
}
|
|
//console.log(new Error().stack);
|
|
this.useConns = null;
|
|
}
|
|
|
|
getNowTime() {
|
|
return this.nowTime;
|
|
}
|
|
|
|
getNowDaySeconds() {
|
|
return this.getNowDaySeconds(this.getNowTime());
|
|
}
|
|
|
|
getDaySeconds(utcTime) {
|
|
|
|
}
|
|
|
|
rspErr(errCode, errMsg) {
|
|
utils.rspErr(this.rsp, errCode, errMsg);
|
|
}
|
|
|
|
rspOk() {
|
|
utils.rspOk(this.rsp);
|
|
}
|
|
|
|
rspData(data) {
|
|
utils.rspData(this.rsp, data);
|
|
}
|
|
|
|
dieErr(errCode, errMsg) {
|
|
this.rspErr(errCode, errMsg);
|
|
}
|
|
|
|
throwError(errCode, errMsg) {
|
|
throw new error.InternalError(errCode, errMsg);
|
|
}
|
|
|
|
request(name, defVal = null) {
|
|
return name in this.req.query ? this.req.query[name] : defVal;
|
|
}
|
|
|
|
requestToJson() {
|
|
return utils.jsonEncode(this.req.query);
|
|
}
|
|
|
|
async getMarketDb() {
|
|
const idx = 0;
|
|
const dbKey = 'MarketDb' + idx;
|
|
if (this.useConns[dbKey]) {
|
|
return this.useConns[dbKey];
|
|
}
|
|
const {err, conn} = await app.getDbConn(dbKey);
|
|
if (err) {
|
|
console.log(err);
|
|
}
|
|
//console.log(new Error().stack);
|
|
if (!err && conn) {
|
|
this.useConns[dbKey] = conn;
|
|
}
|
|
return conn;
|
|
}
|
|
|
|
createModel(name) {
|
|
return modelsFactory.create(name, this);
|
|
}
|
|
|
|
createService(name) {
|
|
return serviceFactory.create(name, this);
|
|
}
|
|
|
|
getMeta(name, key) {
|
|
return metaFactory.getMetaByKey(name, key);
|
|
}
|
|
|
|
callMetaStatic(name, method, ...args) {
|
|
return metaFactory.callMetaStatic(name, method, this, ...args);
|
|
}
|
|
|
|
traverseMetaList(name, cb) {
|
|
return metaFactory.traverseMetaList(name, cb);
|
|
}
|
|
|
|
callMetaFactory(name, ...args) {
|
|
return metaFactory[name](this, ...args);
|
|
}
|
|
|
|
async marketConn(method, ...args) {
|
|
const conn = await this.getMarketDb();
|
|
const ret = await conn[method](...args);
|
|
if (ret.err){
|
|
this.throwError(500, 'internal error');
|
|
log.error(ret.err);
|
|
return;
|
|
}
|
|
if (utils.hasKey(ret, 'row')) {
|
|
return ret['row'];
|
|
} else if (utils.hasKey(ret, 'rows')) {
|
|
return ret['rows'];
|
|
} else {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
}
|
|
|
|
module.exports = Session;
|