Repository navigation
Description
Because the dicussion is spread across many issues and PRs, I wanted to open a new issue to discuss the future syntax for model definition.
Currently, besides the old define(), this syntax is possible in v4.0.0-1:
export class User extends Model {
get fullName() {
return this.firstName + ' ' + this.lastName;
}
set fullName(fullName) {
const names = fullName.split(' ');
this.lastName = names.pop();
this.firstName = names.join(' ');
}
}
User.init(({
username: {
type: DataTypes.STRING,
primaryKey: true
},
lastName: DataTypes.STRING,
firstName: DataTypes.STRING,
}, { sequelize })If you prefer to not do the initialization (which also attaches the connection to the model) inside the model file, but rather from a model index file, this is also possible:
export class User extends Model {
get fullName() {
return this.firstName + ' ' + this.lastName;
}
set fullName(fullName) {
const names = fullName.split(' ');
this.lastName = names.pop();
this.firstName = names.join(' ');
}
static init(sequelize) {
super.init({
username: {
type: DataTypes.STRING,
primaryKey: true
},
lastName: DataTypes.STRING,
firstName: DataTypes.STRING,
}, { sequelize })
}
}With the help of a decorator library and Babel transpilation, this is also possible:
@Options({ sequelize })
@Attributes({
username: {
type: DataTypes.STRING,
primaryKey: true
},
lastName: DataTypes.STRING,
firstName: DataTypes.STRING,
})
export class User extends Model {
get fullName() {
return this.firstName + ' ' + this.lastName;
}
set fullName(fullName) {
const names = fullName.split(' ');
this.lastName = names.pop();
this.firstName = names.join(' ');
}
}And with TypeScript you can go even further:
@Options({ sequelize })
export class User extends Model {
@Attribute({
type: DataTypes.STRING,
primaryKey: true
})
public username: string;
@Attribute(DataTypes.STRING)
public firstName: string;
@Attribute() // Type is inferred as DataTypes.STRING
public lastName: string;
get fullName(): string {
return this.firstName + ' ' + this.lastName;
}
set fullName(fullName: string) {
const names = fullName.split(' ');
this.lastName = names.pop();
this.firstName = names.join(' ');
}
}BUT we definitely do not want to require the usage of any transpiler. The Model.init() API feels a bit weird, especially how the sequelize connection is passed. Some thoughts:
- If we want to make models independent one day from connections, this is has the benefit of easily omitting the
sequelizeoption - But we would probably still need to require that models are registered in a model manager, so we could inverse the syntax (something like
sequelize.add(Model)instead of passing the connection. That is not implemented atm though, currently the model needs to know about the connection.
Please chime in and share your thoughts and ideas!
Issues/PRs for reference: #5898 #6439 #5877 #5924 #5205 #4728
Activity
felixfbecker commentedon Aug 31, 2016
@leebenson
So the attribute configuration is defined as an attribute
nameon the model prototype? Is that even supported syntax in Node 4/6? Is that the attribute initializer proposal? If yes, I don't think we should put the configuration directly on the prototype per-attribute. It should sit underattributes, as it does now. And we shouldn't try to make JavaScript look like TypeScript by abusing property initializers.leebenson commentedon Aug 31, 2016
The decorator proposal is in flux, so I can't say whether that will be a future ECMAScript standard. That's basically what mobx do right now, and it works well.
In the meantime, this is how I'm handling loading models in v4. I'd appreciate your advice if you think this abuses the current API in any way.
Model loader
(influenced by Sequelize CLI 2.3; updated to match my environment)
Sample Model definition (in this case, 'Session')
Invoking the above inside an async function seems to work perfectly...
... which returns the expected output:
leebenson commentedon Aug 31, 2016
A few reasons why I chose the syntax in the above post.
static fieldsobject at the class level gives me the 'class encapsulation' I was looking for without relying on an ECMAScript proposal that's in flux.Sequelize.Modeland exporting it as the default. This is a good separation of concerns, I think - previously, I was doing thesequelize.define()separately inside of each model file and wound up with repeated boilerplate for every new table definition.tableNameproperty.felixfbecker commentedon Sep 1, 2016
@leebenson
See my previous comment. Yes, decorators are still a proposal, but the complete Angular 2 framework is already built on it and that is now at a release candidate, people already use this in production and it works very well.
Please note that class properties can not be used in Node 4/6. It is a Stage 1 proposal, while decorators are already Stage 2. So the API you are proposing will not work without transpilation either, just like a decorator API.
I think aestetically, a static property and a decorator are on the same level, but decorators fit the use case better semantically (you decorate the class with metadata) and they have the benefit of normalization, while the class property would result in unexpected behaviour and would still require a seperate
.init()call.I agree.
This is already implemented in 4.0.0-1. The
tableNamewas just an example of passing options, I removed it to clarify it.I don't get what you are trying to say. Imo a model file should be as self-contained as possible. I actually even use late imports instead of the
module.exports = function(sequelize, DataTypes) {pattern, so I don't even need a model index file that "wires up" the models, they wire up themselves, including associations. I tried to highlight a bit of this in my PR to update the docs, see https://github.com/felixfbecker/sequelize/blob/76590ab17ad8d160272a7e02bd7b381bc49ae919/docs/docs/models-definition.md#one-file-per-model-patternleebenson commentedon Sep 1, 2016
No arguments there. I'm already using decorators with mobx too, and I love them! I just couldn't find a better fit for wiring up field definitions than a static property on the class. A decorator function seemed like overkill.
What I'm saying is that defining field types within the body of the class seems like a better approach.
In your example, you do this...
This part irks me...
You've created a class to extend
Model, but it's blank. Presumably the only benefit here is that you've removed the need to explicitly definetableName.Then in a separate call, you initialise it with
.init()and feed in the field definitions.IMO, it looks better to keep them defined within the class. Whether it's a decorator or a static property is less relevant... more so is that syntax outside of the class makes it hard to reason about exactly what fields the model contains. I have 500+ lines of field definitions and boilerplate in some places... I'd rather keep that inside the class than stick it where my
.init()code goes, which could well be somewhere outside of the model definition entirely.Just my personal preference.
felixfbecker commentedon Sep 1, 2016
Yes,
init()after the class is definitely the ugly part about the API. But as I said, there is no way to do it without using a transpiler atm (and then decorators are a better solution). And we of course also still havedefine().leebenson commentedon Sep 1, 2016
Another option is static method... they've been in Node since 4+ and don't require any transpilation at all:
mickhansen commentedon Sep 1, 2016
@felixfbecker Is the model name taken from the class name? In that case we need a way to override it because a lot of people generally have lower case model names but would probably have lint rules telling them to have uppercase class names
felixfbecker commentedon Sep 1, 2016
@leebenson Yes, but imo having a method that always returns the same configuration object just because the language doesn't have property declarations yet is syntax abuse and DSLish.
@mickhansen yes, the model name is the
nameproperty of the class, which is the class name. It is a native property of all functions. It can be overridden with themodelNameoption or when usingsequelize.define(). But to be honest I think we should use PascalCase naming in the docs because it is confusing whenUser.name !== 'User'.leebenson commentedon Sep 1, 2016
@felixfbecker re: lower casing, I'm currently doing it explicitly like this (in my model loader)
With my session definitions now looking closer to this:
So a
Sessionclass becomes asessionstable.I agree with you that a method returning the same static data isn't ideal. It's an alternative to requiring a transpilation step, though, and it's only run once. Plus, it's an opportunity to bind the current
sequelizeclient as a parameter, in case definitions somehow rely on it.Hard to get that with a static class attribute or a decorator that's outside of the definition scope.
felixfbecker commentedon Sep 1, 2016
Please note that
tableNameandmodelNameare two different options.I am highly against this. In a static method, I expect
thisto be the class. Or are you not talking about binding?It's super simple to share the sequelize instance is to simply have a module that exports it, and require it in the model files.
mickhansen commentedon Sep 1, 2016
Definitely, just need to make sure it's possible to reconfigure
leebenson commentedon Sep 1, 2016
I know, but in the absence of either being set explicitly, the pluralised version of class.name is used, right?
I think this is what @mickhansen was referring to. It threw me off too. Hence the pluralize hack above.
Model.initought to lowercase the class name before it implicitly pluralises it for use as a model/table name.Binding as a parameter. Not to
this.So you can do something like...
I do use this elsewhere on my class, btw, for things like GraphQL...
It keeps model logic neatly in one place, without polluting any model instance.
56 remaining items
epicbagel commentedon Jul 10, 2017
@leebenson one option is to spin this off into a separate library (e.g. sequelize-model-builder) that could hide some of the messiness with "init" rather than working to get this into Sequelize while annotations still require transpilation.
It's something I've considered working on. We have a large number of model definitions and the approach you posted above is along the lines of the direction we'll like to take.
dcworldwide commentedon Jul 10, 2017
For typescript users I think typeorm completely nailed their orm api. https://github.com/typeorm/typeorm. Well worth reviewing for inspiration.
felixfbecker commentedon Jul 10, 2017
What exactly is the "messiness" with
init? It's just a static constructor. It needs to normalise options, and initialises the model. This is not possible with static constructors, and decorators are simply a way to invoke that logic.Both typeorm and sequelize-typescript use terrible patterns for associations that will plain out break with native ES6 modules in Node:
this is so incredibly hacky, a cyclic dependency that only works because of TS compiler implementation details when transpiling to CommonJS.
Why does a "TypeScript library" for Sequelize have so many lines of code?!
https://github.com/felixfbecker/sequelize-decorators is 39 lines and requires no
initcall either.snewell92 commentedon Jul 10, 2017
re: "terrible patterns" Ough! Ouch. 🗡 💀
re: messiness
In regards to the messiness... yeah I stand with felix on this one. It's just not
messy enoughreally messy at allto warrant wrapping the initialization process nor factoring that out. In my context, I prefer the single class with minimal decorator approach because that communicates more to my team.However, if I wasn't constrained by communicating to an older team, I would rather just use sequelize plainly ('idiomatically' if you will). If I wanted to cut down on lines of code, the decorator syntax OR static init would be leaner than what I have now.
None of what @felixfbecker or @leebenson have suggested above is messy, it's an improvement over what existed.
If you disagree, provide code samples to try to demonstrate some friction in the way you define your models and the way you wish you could define them, and then discussion can proceed, but I'm not seeing anything messy (even as someone who prefers the class approach).
Implementation aside
Also, if the friction is just a repeated init function for all your models, and you think it's violating SRP... you can factor that out in its own function, or perhaps have all your models inherit from the same prototype, or perhaps do a more oopy 'base class' dealio.
The problem you'd run into is I'm willing to bet not all your init functions are created equal. There's some good reasons the sequelize team has it still.
As it stands, Sequelize lets you choose how to do it. We are using JavaScript after all
, anything is possible!You could even create the model builder yourself as a specialized model factory if you really wanted to. If you want it, just do it! Then share it here and the sequelize team will use what they think is valuable, and keep in userland what they believe to be best left in userland.
leebenson commentedon Jul 10, 2017
Except operator overloads, first-class decorator support, list comprehensions, transactions that don't get lost inside of Promise chains... 😛
keyiis commentedon Aug 21, 2017
sequelize come on! ! ! i won't change to another orm(typeorm),i hope decorator become standard library in sequelize code and doc!
RobinBuschmann commentedon Aug 26, 2017
@felixfbecker This is not true. ES6 modules are indeed able to handle cyclic dependencies. So this is not hacky at all and has nothing to do with 'implementation details' of the tsc.
There are some browser(chrome canary, safari technology preview) out there, which implements ES6 modules natively. If you run the following code snippets (which includes a cyclic dependency) in one of these browsers, you will see that it works very well.
zhanwenchen commentedon Sep 15, 2017
After all night of tweaking, I finally have a working example, based on @leebenson and @felixfbecker's posts on this thread. @snewell92 take a look at this.
@felixfbecker one needs to explicitly
returnsuper.init({...}, {sequelize});instatic init(...). The childinitfunction should also take a sequelize instance.To use, put all 4 files in an empty directory and do
node index.js.@mickhansen In my example, using Node 6.11.3 LTS, I did not need a transpiler for
static.index.js
Post.js
User.js
Comment.js
snewell92 commentedon Sep 15, 2017
Dang, neat!
Related tidbit
This is not strictly related, but I do something similar for initializing services in feathers by using
fsto read a directory structure.One thing I commented on for a future item, is that if any of my services depend on one another, the way I'm initializing my services won't work.
However, the way sequelize splits out associating models together after the models are all initialized could apply to that domain too. And thus, as long as my services aren't using each other in the
initphase, I could compose them or use them in theassociatephase. Exactly how your POC works.sylver commentedon Nov 6, 2017
Great post and thanks @zhanwenchen for this very detailed example which helped me a lot !
However I'm still having issues figuring out how to define hooks, getters and setters in this case. I tried static methods, instance methods, direct definition like
MyModel.beforeCreate = ..., etc. I'm unable to get it triggered whatever I try.Would you mind to give an example of the right way to do it please ?
UnbrandedTech commentedon Jan 17, 2018
@Sylv3r SUPER late to the game but I think you can add it to the
initoptions...Haven't tested this, still researching if this is an ok pattern to follow. (The whole
class extendsthing)skrubinator88 commentedon Feb 15, 2018
Wow this helped me a lot, thanks a ton!
jnnkky commentedon Mar 17, 2018
Is there a reason why this approach is not documented anywhere in the documentation? Should I be using this or the normal .define way?
UnbrandedTech commentedon May 2, 2018
Just to confirm, my previous model does indeed work and is in production.
tsirolnik commentedon Oct 15, 2018
Anyone had success with instance methods? Can't make it work for some reason. https://stackoverflow.com/questions/52813078/sequelize-es6-model-methods-no-existing