I spent an hour or two today trying to create a custom TypeORM FindOperator. I found a few results searching Google but all of them seem to be outdated and don’t work with the current release of TypeORM. Ultimately the solution was so easy, almost too easy.

I wanted to create a TypeORM operator for the Postgres Regex Match Operator. My first approach was to subclass FindOperator and override toSql which seems to now be called getSql. But that did not work (seems TypeORM ignores that now and builds the query based on the type property instead.) That’s probably the right thing to do because it allows them to implement operators differently based on the type of database TypeORM is connecting to. But that doesn’t help me, I just need PostgreSQL. So without further ado, here’s my solution:

import { Raw } from "typeorm";

let uid = 0;
export function RegexMatches(regex: string) {
  const paramId = `regex${uid++}`;
  return Raw((pathAlias: string) => `${pathAlias} ~ :${paramId}`, {
    [paramId]: regex,
  });
}

Yep, just wrap the Raw operator and output the condition that you want to match. In my case, the ~ Regex (case sensitive) Match operator. TypeORM escapes the path alias for you and your regex is passed as a parameter, so no problems with SQL injection here if your regex is built dynamically. The parameter name used must be unique if we want to use the operator more than once in a query, so we’ll create a unique id for that.