Skip to content

Instantly share code, notes, and snippets.

@mustofa-id
Created June 24, 2023 02:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mustofa-id/2f5c7525e373aa248caecea536620f64 to your computer and use it in GitHub Desktop.
Save mustofa-id/2f5c7525e373aa248caecea536620f64 to your computer and use it in GitHub Desktop.
Node postgres (pg) template string
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);
}
@mustofa-id
Copy link
Author

Usage:

const people_query = sql`select id, name, age from person where age < ${35} limit ${20}`;
await client.query(people_query);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment