/**
* Takes an object and returns a Postgres json_build_object()
* @param obj A map of any shape
* @param alias Column alias
* @returns json_build_object() SQL code
*/
export function jsonBuildObjectSql(
obj: Record<string, unknown>,
alias?: string,
checkFieldForNull?: string
): string {
return (
(checkFieldForNull
? `case when ${checkFieldForNull} is not null then `
: '') +
'json_build_object(' +
Object.entries(obj)
.map(pair => [`'${pair[0]}'`, pair[1]])
.join(', ') +
')' +
(checkFieldForNull ? ' else null end' : '') +
(alias ? ` as ${alias}` : '')
);
}
/**
* Takes an object and returns a Postgres json_build_object()
* @param obj A map of any shape
* @param alias Column alias
* @returns json_build_object() SQL code
*/
export function jsonBuildObjectSql(
obj: Record<string, unknown>,
alias?: string,
checkFieldForNull?: string
): string {
return (
(checkFieldForNull
? `case when ${checkFieldForNull} is not null then `
: '') +
'json_build_object(' +
Object.entries(obj)
.map(pair => [`'${pair[0]}'`, pair[1]])
.join(', ') +
')' +
(checkFieldForNull ? ' else null end' : '') +
(alias ? ` as ${alias}` : '')
);
}