TypeORM Parameterized Query Safety
Keep TypeORM queries injection-safe with parameter placeholders, typed find options, and a guard against unsafe raw SQL fragments.
Code
import { DataSource, Entity, PrimaryGeneratedColumn, Column } from 'typeorm';
@Entity({ name: 'accounts' })
class Account {
@PrimaryGeneratedColumn() id!: number;
@Column() email!: string;
@Column() status!: string;
}
const dataSource = new DataSource({
type: 'postgres',
url: process.env.DATABASE_URL,
entities: [Account],
});
await dataSource.initialize();
const repo = dataSource.getRepository(Account);
async function searchByDomain(domain: string) {
// LIKE 模式里的通配符要转义,值仍走参数绑定
const escaped = domain.replace(/[\\%_]/g, (ch) => '\\' + ch);
return repo
.createQueryBuilder('account')
.where('account.email LIKE :pattern', { pattern: '%' + escaped + '%' })
.andWhere('account.status = :status', { status: 'active' })
.orderBy('account.id', 'ASC')
.limit(50)
.getMany();
}
function rejectUnsafeFragment(input: string): never {
if (/;|--|\/\*/.test(input)) {
throw new Error('suspicious SQL fragment rejected');
}
throw new Error('raw fragments are not allowed');
}
const matches = await searchByDomain('example.com');
console.log('accounts found:', matches.length);
await dataSource.destroy();Report a problem with this exampleOpens a pre-filled issue on GitHub.