Created
June 24, 2023 02:09
-
-
Save mustofa-id/2f5c7525e373aa248caecea536620f64 to your computer and use it in GitHub Desktop.
Node postgres (pg) template string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import type { CustomTypesConfig, QueryConfig } from 'pg'; | |
export class Template_Query_Config implements QueryConfig { | |
private name_?: string; | |
private types_?: CustomTypesConfig; | |
constructor(private readonly strings: string[], readonly values: any[]) {} | |
get text(): string { | |
return ( | |
this.strings | |
// join strings to query text | |
.reduce((prev, curr, i) => prev + '$' + i + curr) | |
// remove whitespace | |
.replace(/(?:\n\s*)/g, ' ') | |
); | |
} | |
get name(): string | undefined { | |
return this.name_; | |
} | |
get types(): CustomTypesConfig | undefined { | |
return this.types_; | |
} | |
private merge(current: Template_Query_Config, statement: string | Template_Query_Config): void { | |
if (statement instanceof Template_Query_Config) { | |
current.strings[current.strings.length - 1] += statement.strings[0]; | |
current.strings.push(...statement.strings.slice(1)); | |
current.values.push(...statement.values); | |
} else { | |
current.strings[current.strings.length - 1] += statement; | |
} | |
} | |
append(statement: string | Template_Query_Config): Template_Query_Config { | |
if (!statement) return this; | |
this.merge(this, statement); | |
return this; | |
} | |
concat(statement: string | Template_Query_Config): Template_Query_Config { | |
const clone = new Template_Query_Config([...this.strings], [...this.values]); | |
this.merge(clone, statement); | |
return clone.with_name(this.name_).with_types(this.types_); | |
} | |
with_name(name?: string): Template_Query_Config { | |
this.name_ = name; | |
return this; | |
} | |
with_types(types?: CustomTypesConfig): Template_Query_Config { | |
this.types_ = types; | |
return this; | |
} | |
} | |
export function sql(query: TemplateStringsArray, ...values: any[]): Template_Query_Config { | |
const strings = Array.from(query); | |
return new Template_Query_Config(strings, values); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage: