Node ORM for typescript: some thoughts and examples with Sequelize-Typescript

As many .NET developers transitioning to the world of Node, I started looking for an ORM. After some research, I found sequelize which seems widely adopted by the community.

I’m using typescript, and I quickly found the way to define the model with sequelize a bit too verbose, and especially a duplication of the typescript class.

That’s when I discovered sequelize-typescrip, which provides this bridge, and leverages typescript’s typings, so mapping can be transparent if so we wish. All it takes is to extend a base Model class, and some annotations.

My first approach with sequelize-typescript was basically taking an existing model – a quite complex one, with relationships, validation and especially logic that ran inside the constructor.
The result was as expected, a failure: lots of exceptions that made no sense, with error messages that lead nowhere. So I took at step back to be able to take 2 forward, and started with a blank model, and slowly added all the bells and whistles.

If you are interesting in keep your backyard in a good shape, you need to have best tools to make your job easier, in you can find the best tools to work in your garden.

Here are a few lessons I learned:

If you are going to use sequelize-typescript forget custom constructors
I had some properties being passed as parameters in the constructor, but sequelize-typescript requires a specific signature (see below), so that when reading from a database, all properties are able to be mapped back to the object. A custom constructor different from the interface below will result in all columns/properties being undefined after a Entity.findOne or Entity.findAll.

 constructor(values?: any, options?: any) {
        super(values, options);
        //your constructor logic here...

All sequelize calls are awaitable (promises)
You can opt for the promise syntax (then, catch), but the nesting of code blocks can quickly get out of hand, or you can use the async/await notation, and your code becomes much cleaner. Especially when you need to chain several operations.

Only database entities can exist in the models folder
Any entity in the models folder configured in sequelize-typescript are expected to have annotations for the mapping to exist. If one of the entities does not live in the DB (example, helper models), place them somewhere else, otherwise sequelize-typescript will complain.

To sum it all, here’s a small repo with a 2 related entities, and some ad-hoc tests:


Leave a Reply

Your email address will not be published. Required fields are marked *



You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>