rapid-db
Version:
Rapid Database Interface
84 lines (79 loc) • 2.64 kB
JavaScript
/**
* Copyright (c) 2017 Lucky Byte, Inc.
*/
const debug = require('debug')('db');
const winston = require('winston');
const moment = require('moment');
/**
* 监视数据库错误事件
*/
let init_opts = {
error: (err, evt) => {
if (evt.query) {
winston.error(`执行SQL[${evt.query.trim()}]错误:`, err.message);
} else {
winston.error('数据库操作错误:', err.message);
}
}
}
/*
* 如果是开发环境,则开启数据库日志追踪
*/
if (process.env.NODE_ENV !== 'production') {
init_opts = Object.assign({
connect: (client, dc, is_fresh) => {
if (is_fresh) {
winston.info('建立新数据库连接成功 ...');
} else {
winston.info('重连数据库成功 ...');
}
},
disconnect: (client, dc) => {
winston.info('断开数据库连接 ...');
},
query: (evt) => {
winston.info(`开始执行 SQL:[${evt.query.trim()}]`);
},
receive: (data, result, evt) => {
const reduce_object = (object) => {
for (k in object) {
if (object[k]) {
let v;
if (typeof object[k] === 'object') {
v = JSON.stringify(object[k]);
} else {
v = object[k].toString();
}
if (v.length > 50) {
object[k] = v.substr(0,50) + `...(${v.length} 字节)`;
}
}
}
}
let object = JSON.parse(JSON.stringify(data));
if (object instanceof Array) {
for (let i = 0; i < object.length; i++) {
reduce_object(object[i]);
}
} else {
reduce_object(object);
}
const fmt_text = JSON.stringify(object, null, 2);
winston.info(`[${evt.query.trim()}]执行完毕,返回结果:`, fmt_text);
},
}, init_opts);
}
const pgp = require('pg-promise')(init_opts);
pgp.pg.types.setTypeParser(1114, (val) => { // timestamp
return val ? moment(val) : null;
});
pgp.pg.types.setTypeParser(1184, (val) => { // timestamp
return val ? moment(val) : null;
});
pgp.pg.types.setTypeParser(1082, (val) => { // timestamp
return val ? moment(val) : null;
});
pgp.pg.types.setTypeParser(1083, (val) => { // timestamp
return val ? moment(val, 'HH:mm:ss') : null;
});
module.exports = pgp;