-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
70 lines (63 loc) · 1.97 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
const highlight = require("cli-highlight").highlight;
const sqlFormatter = require("sql-formatter");
const chalk = require("chalk");
// The sqlFormatter library splits all the selected fields onto their own lines.
// Very readable, but a lil verbose in a terminal. This takes those lines and
// scrunches them back together.
function scrunchSQLSelect(query) {
let inColumns = false;
const lines = query.split("\n");
const scrunched = [];
for (let line of lines) {
if (line.startsWith("SELECT")) {
inColumns = true;
scrunched.push(line);
} else if (!inColumns) {
scrunched.push(line);
} else if (inColumns && line.startsWith("FROM")) {
inColumns = false;
scrunched.push(line);
} else if (inColumns) {
scrunched[scrunched.length - 1] += line;
}
}
return scrunched.join("\n");
}
function createNiceSequelizeLoggerConfig(logger = console) {
function sequelizeLogger(log, responseTime, query) {
if (process.env.LOG_SQL_STATEMENTS === "true") {
if (log.includes("pg_attribute")) return;
const cleaned = log.replace(/Executed \(default\):/, "");
const formatted = sqlFormatter.format(cleaned);
const scrunched = scrunchSQLSelect(formatted);
const highlighted = highlight(scrunched, {
language: "sql",
ignoreIllegals: true,
});
const header = `EXECUTED SQL (${responseTime / 1000}ms)`;
if (logger.group) {
logger.group(header);
}
else {
logger.log(chalk.bgCyan(header));
}
logger.log(highlighted);
if (query.bind) {
query.bind.forEach((value, index) => {
logger.log(
chalk.green(`$${index + 1}: `),
JSON.stringify(value, null, 2),
);
});
}
if (logger.groupEnd) {
logger.groupEnd();
}
}
}
return {
logging: sequelizeLogger,
benchmark: true,
};
}
module.exports.createNiceSequelizeLoggerConfig = createNiceSequelizeLoggerConfig;