UNPKG

prisma-query-formatter

Version:

Small utility for Prisma query formatting and param substitution in logs

105 lines (104 loc) 3.34 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.formatQuery = exports.parseParams = exports.escapeWhitespace = void 0; const escapeWhitespace = (param) => { return param.replace(/[\f\n\r\t\v]/g, (match) => { if (match === "\f") return "\\f"; if (match === "\n") return "\\n"; if (match === "\r") return "\\r"; if (match === "\t") return "\\t"; if (match === "\v") return "\\v"; return match; }); }; exports.escapeWhitespace = escapeWhitespace; const parseParams = (params) => { const input = params.replace(/^\[([^]*)]$/, "$1"); const parsedParams = []; if (!input) return parsedParams; const stack = []; let currentBuffer = ""; let inQuotes = false; let inXml = false; for (let i = 0; i < input.length; i++) { let currentChar = input[i]; if (currentChar === '"' && input[i - 1] !== "\\") { inQuotes = !inQuotes; } if (inQuotes) { currentBuffer += currentChar; continue; } else if (currentChar === "<" && input.substring(i, i + 15) === "<{} bytes blob>") { parsedParams.push("<{} bytes blob>"); i += 15; continue; } if (currentChar === "<") { inXml = true; if (input[i + 1] === "/" && stack[stack.length - 1] === "<") { stack.pop(); } else if (input[i + 1] !== "?" && input[i + 1] !== "!") { stack.push("<"); } } else if (currentChar === ">") { inXml = false; } else if (currentChar === "{") { stack.push("{"); } else if (currentChar === "}" && stack[stack.length - 1] === "{") { stack.pop(); } else if (currentChar === "[") { stack.push("["); } else if (currentChar === "]" && stack[stack.length - 1] === "[") { stack.pop(); } if (currentChar === "," && !stack.length && !inXml) { parsedParams.push(currentBuffer); currentBuffer = ""; } else { currentBuffer += currentChar; } } if (currentBuffer) { parsedParams.push(currentBuffer); } return parsedParams; }; exports.parseParams = parseParams; const formatQuery = (query, params, options = {}) => { try { query = query.replace(/\s/g, " ").replace(/\s{2,}/g, " "); const placeholders = query.match(/(\?|\$\d+)/g) || []; const parsedParams = (0, exports.parseParams)(params); if (placeholders.length !== parsedParams.length) { throw new Error("Number of placeholders and params doesn't match"); } if (parsedParams.length > 0) { query = query.replace(/(\?|\$\d+)/g, () => { const param = parsedParams.shift() || ""; return options.paramTransformer ? options.paramTransformer(param) : param; }); } return query.trim(); } catch (error) { if (options.throwOnError) { throw error; } return `${query} ${params}`; } }; exports.formatQuery = formatQuery;