UNPKG

@launchql/core

Version:

LaunchQL Package and Migration Tools

76 lines (75 loc) 2.8 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.transform = exports.transformProps = void 0; const pgsql_deparser_1 = require("pgsql-deparser"); const pgsql_parser_1 = require("pgsql-parser"); /** * Recursively transforms the properties of an object based on a transformation map. * * @param obj - The object to transform. * @param props - A map of properties and their transformation rules. * @returns A new object with transformed properties. */ const transformProps = (obj, props) => { let copy; // Handle primitive types, null, or undefined if (obj === null || typeof obj !== 'object') return obj; // Handle Date if (obj instanceof Date) { copy = new Date(); copy.setTime(obj.getTime()); return copy; } // Handle Array if (Array.isArray(obj)) { copy = []; for (let i = 0, len = obj.length; i < len; i++) { copy[i] = (0, exports.transformProps)(obj[i], props); } return copy; } // Handle Object if (obj instanceof Object || typeof obj === 'object') { copy = {}; for (const attr in obj) { if (Object.prototype.hasOwnProperty.call(obj, attr)) { if (props.hasOwnProperty(attr)) { const propRule = props[attr]; if (typeof propRule === 'function') { // Apply function transformation copy[attr] = propRule(obj[attr]); } else if (typeof propRule === 'object' && propRule !== null) { // Apply value-based transformation if (propRule.hasOwnProperty(obj[attr])) { copy[attr] = propRule[obj[attr]]; } else { copy[attr] = (0, exports.transformProps)(obj[attr], props); } } } else { copy[attr] = (0, exports.transformProps)(obj[attr], props); } } } return copy; } throw new Error("Unable to copy obj! Its type isn't supported."); }; exports.transformProps = transformProps; /** * Parses a SQL statement, transforms its properties, and regenerates the SQL. * * @param statement - The SQL statement to transform. * @param props - A map of properties and their transformation rules. * @returns The transformed SQL statement. */ const transform = async (statement, props) => { let tree = await (0, pgsql_parser_1.parse)(statement); tree = (0, exports.transformProps)(tree, props); return await (0, pgsql_deparser_1.deparse)(tree); }; exports.transform = transform;