DEV Community

Joe Flateau
Joe Flateau

Posted on • Originally published at joeflateau.net on

4 2

Creating custom TypeORM Operators

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,
  });
}

Enter fullscreen mode Exit fullscreen mode

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.

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay