sequelize / sequelize-auto

Automatically generate bare sequelize models from your database.
2.9k stars 527 forks source link

Using getAttributes to re-initialize models with customizations (getters/setters) #654

Open patricktyndall opened 1 year ago

patricktyndall commented 1 year ago

An idea for using sequelize-auto in scenarios where type-based customizations (getters/setters) are needed. Appreciate any feedback.

My app uses custom getters/setters so we can use integers to represent timestamptz columns (unix seconds). All timestamptzs are done this way.

As far as I can tell, there's no way to configure this globally for a specific column type in sequelize (or sequelize-auto). This is a blocker for adopting this lib.

So I've been looking for workarounds to achieve this so we can use sequelize-auto without breaking existing code:

One thing does come to mind: Using a custom initModels file, initialize a model from sequelize-auto, then call getAttributes on it to list the columns, then create a new model and loop through the columns to re-add them to my new model, but with type-based overrides.

 {
   type: BOOLEAN {},
   allowNull: false,
   defaultValue: false,
   Model: restaurant,
   fieldName: 'is_dine_in_only',
   _modelAttribute: true,
   field: 'is_dine_in_only'
 }

This seems like enough info for me to create my own model with the necessary overrides. In other words, I just need sequelize-auto to be a "schema parsing" tool, and I can intercept its models to create my own with the generated schema info.

Here are some concerns I have:

Can anyone critique this, or has anyone tried this approach?