Skip to content

SEQUELIZE AND 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.

Using typescript, 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-typescript, 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.

The 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.

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.

1
2
3
4
constructor(values?: any, options?: any) {
super(values, options);
//your constructor logic here...
}
code snippet (typescript)

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: https://github.com/CarlosRodrigues/Sequelize-typescript-example

Cheers!

Published inBackendDatabasesNode.js

Be First to Comment

Leave a Reply