pattern/enterprise/query-object
- Bun
- PostgreSQL
- TypeScript
- node-postgres
- Docker
A consulta com filtros opcionais vira um objeto composto por métodos: cada método acrescenta um predicado parametrizado e colunas externas passam por allowlist. Use em listagens com filtros combináveis, sem SQL injection.
pattern/enterprise/query-object
Cenário
Extrato com PIX e TED entre R$ 200,00 e R$ 900,00, do menor para o maior.
Planta
Sequência4 passos — reproduza para seguir o fluxo
Como funciona
4passos
A consulta com filtros opcionais vira um objeto composto por métodos, com predicados parametrizados e allowlist de colunas
Esconde cada passo: lembre antes de tocar para revelar.
Vocabulário compartilhado
QueryTransaction: um método por filtro, devolve o próprio objeto
build() numera os placeholders; nenhum valor entra no SQL
orderBy fora da allowlist → ErrorQueryInvalid
Quem executa recebe { sql, params } e chama pool.query
Trade-offs
O que se ganha, o que se paga
Vantagens
Sem SQL injection por construção
build() testável sem banco
Custos
Mais código que SQL à mão
CTE e subquery ficam de fora
Código
pattern/enterprise/query-object
7 arquivos./
sql/
src/
Executar com Docker
./docker.shuntil docker exec query-object-db pg_isready -h 127.0.0.1 -U postgres >/dev/null 2>&1; do sleep 1; donebun install# dependênciasbun run demo# roda o cenáriodocker rm -f query-object-dbSaída: SQL com $1 a $5, os parâmetros à parte e as linhas pix R$ 400,00, ted R$ 500,00, pix R$ 800,00 e ted R$ 900,00.
Código
src/demo.ts// Demo: a statement query composed by methods; every value becomes a numbered parameter and ORDER BY a whitelisted column.
import pg from "pg";
type TransactionType = "pix" | "ted" | "boleto" | "card";
class ErrorQueryInvalid extends Error {
override name = "ErrorQueryInvalid";
}
// ORDER BY cannot be a parameter, so the column is only ever one of these.
const SORT_COLUMNS = new Set(["created_at", "amount_cents"]);
const PAGE_SIZE_DEFAULT = 20;
// Builds SQL and never touches the database: each method adds one predicate.
class QueryTransaction {
private readonly conditions: ((placeholder: (value: unknown) => string) => string)[] = [];
private sort = { column: "created_at", direction: "DESC" as "ASC" | "DESC" };
private pageSize = PAGE_SIZE_DEFAULT;
forAccount(accountId: string): this {
return this.where((p) => `account_id = ${p(accountId)}`);
}
whereTypes(types: TransactionType[]): this {
return types.length ? this.where((p) => `type = ANY(${p(types)})`) : this;
}
// Both ends inclusive; either may be left open.
whereAmountBetween(minCents?: number, maxCents?: number): this {
if (minCents !== undefined) this.where((p) => `amount_cents >= ${p(minCents)}`);
if (maxCents !== undefined) this.where((p) => `amount_cents <= ${p(maxCents)}`);
return this;
}
orderBy(column: string, direction: "ASC" | "DESC" = "DESC"): this {
if (!SORT_COLUMNS.has(column)) throw new ErrorQueryInvalid(`column "${column}" is not allowed in ORDER BY`);
this.sort = { column, direction };
return this;
}
limit(size: number): this {
this.pageSize = size;
return this;
}
build(): { sql: string; params: unknown[] } {
const params: unknown[] = [];
const placeholder = (value: unknown) => `$${params.push(value)}`;
const predicates = this.conditions.map((condition) => condition(placeholder));
const where = predicates.length ? ` WHERE ${predicates.join(" AND ")}` : "";
return { sql: `SELECT type, amount_cents FROM transactions${where} ORDER BY ${this.sort.column} ${this.sort.direction} LIMIT ${placeholder(this.pageSize)}`, params };
}
private where(condition: (placeholder: (value: unknown) => string) => string): this {
this.conditions.push(condition);
return this;
}
}
const pool = new pg.Pool({ connectionString: Bun.env.QUERY_OBJECT_DATABASE_URL ?? "postgres://postgres:postgres@localhost:5432/query_object_db" });
const account = "CC-0001";
// Rewrites the account's transactions, so a second run reads the same twelve rows.
await pool.query("DELETE FROM transactions WHERE account_id = $1", [account]);
await pool.query(
`INSERT INTO transactions (account_id, type, amount_cents, status)
SELECT $1, (ARRAY['pix','ted','boleto','card'])[1 + n % 4], 10000 * n, 'completed' FROM generate_series(1, 12) AS n`,
[account],
);
const { sql, params } = new QueryTransaction().forAccount(account).whereTypes(["pix", "ted"]).whereAmountBetween(20_000, 90_000).orderBy("amount_cents", "ASC").limit(5).build();
console.log(` [SQL] ${sql}\n [PARAMS] ${JSON.stringify(params)}`);
const { rows } = await pool.query<{ type: TransactionType; amount_cents: string }>(sql, params);
console.log(` [ROWS] ${rows.map((row) => `${row.type} R$ ${(Number(row.amount_cents) / 100).toFixed(2)}`).join(", ")}`);
await pool.end();
Nível
intermediário
4/13
Domínio financeiro
Padrões do catálogo que implementa
Infraestrutura
PostgreSQLbanco relacional
postgres:16-alpine:5432
Banco
sql/01_schema.sql
Variáveis de ambiente
Trilhapasso 3 de 6
Lógica de domínio (PoEAA)
Parecidos
Por que se relacionam
Teste rápido
Qual destes combina com Query Object?
Consulta do lado de leitura. Abrir CQRS
Seu progresso
0/157 estudados
Fica salvo só neste navegador.