2019-02-27 16:01:51 +08:00
|
|
|
'use strict';
|
|
|
|
|
2019-02-27 17:40:49 +08:00
|
|
|
const { stringifyForLogs } = require('../utils/logs');
|
2019-02-27 16:01:51 +08:00
|
|
|
|
2019-02-28 18:48:51 +08:00
|
|
|
const TYPES = {
|
|
|
|
QUERY: 'query',
|
|
|
|
JOB: 'job'
|
|
|
|
};
|
|
|
|
|
|
|
|
module.exports = function log(sqlType = TYPES.QUERY) {
|
2019-02-27 16:01:51 +08:00
|
|
|
return function logMiddleware(req, res, next) {
|
2019-02-27 19:51:01 +08:00
|
|
|
const MAX_SQL_LENGTH = (global.settings.logQueries && global.settings.maxQueriesLogLength) || 1024;
|
|
|
|
|
2019-02-27 16:01:51 +08:00
|
|
|
const logObj = {
|
|
|
|
request: {
|
2019-02-28 18:48:51 +08:00
|
|
|
sql: prepareSQL(res.locals.sql, sqlType, MAX_SQL_LENGTH)
|
2019-02-27 16:01:51 +08:00
|
|
|
}
|
2019-02-27 18:59:04 +08:00
|
|
|
};
|
2019-02-27 16:01:51 +08:00
|
|
|
|
2019-02-27 17:40:49 +08:00
|
|
|
res.set('X-SQLAPI-Log', stringifyForLogs(logObj, MAX_SQL_LENGTH));
|
2019-02-27 16:01:51 +08:00
|
|
|
|
|
|
|
return next();
|
|
|
|
};
|
|
|
|
};
|
|
|
|
|
2019-02-28 18:48:51 +08:00
|
|
|
module.exports.TYPES = TYPES;
|
|
|
|
|
|
|
|
function prepareSQL(sql, sqlType, MAX_SQL_LENGTH) {
|
2019-02-27 19:51:01 +08:00
|
|
|
if (!sql || !global.settings.logQueries) {
|
2019-02-27 17:07:56 +08:00
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (typeof sql === 'string') {
|
|
|
|
return {
|
2019-02-28 18:48:51 +08:00
|
|
|
type: sqlType,
|
|
|
|
sql: sql.substring(0, MAX_SQL_LENGTH)
|
2019-02-27 18:59:04 +08:00
|
|
|
};
|
2019-02-27 17:07:56 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
if (Array.isArray(sql)) {
|
|
|
|
return {
|
2019-02-28 18:48:51 +08:00
|
|
|
type: sqlType,
|
|
|
|
sql: sql.map(q => q.substring(0, MAX_SQL_LENGTH))
|
2019-02-27 18:59:04 +08:00
|
|
|
};
|
2019-02-27 17:07:56 +08:00
|
|
|
}
|
|
|
|
|
2019-02-28 18:48:51 +08:00
|
|
|
// other cases from Batch API
|
2019-02-27 17:07:56 +08:00
|
|
|
return {
|
2019-02-28 18:48:51 +08:00
|
|
|
type: sqlType,
|
|
|
|
sql: sql
|
2019-02-27 18:59:04 +08:00
|
|
|
};
|
2019-02-27 16:01:51 +08:00
|
|
|
}
|