pg-camel-case.ts
function snakeToCamel(snakeCase: string){
if(snakeCase.indexOf("_") < 0)
return snakeCase;
var tokens = snakeCase.split(/_+/).filter(function(token){
return (token.length >= 1);
});
if (tokens.length <= 1) {
return snakeCase;
}
var first = tokens.shift().toLowerCase();
var rest = tokens.map(function(token){
return token.charAt(0).toUpperCase().concat(
token.substring(1).toLowerCase()
);
}).join('');
return first.concat(rest);
};
export function handlePgSnakeFieldsToCamel(pg: any) {
const proto = pg?.Client?.Query?.prototype;
if(proto) {
const handleRowDesc = proto.handleRowDescription;
proto.handleRowDescription = function(msg: any) {
msg.fields.forEach(function(field: any){
field.name = snakeToCamel(field.name);
});
return handleRowDesc.call(this, msg);
};
}
}
pg-connection.ts
import dotenv from "dotenv";
import { Pool } from "pg";
import { handlePgSnakeFieldsToCamel } from "./pg-camel-case";
const pg = new Pool({
host: process.env.PG_HOST,
port: Number(process.env.PG_PORT),
user: process.env.PG_USER,
password: process.env.PG_PASS,
database: process.env.PG_DB,
});
if(/* Optional */) {
handlePgSnakeFieldsToCamel(pg);
}
// 현재 연결
export const pgConnection = pg;