You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Would be great to support Sequelize models as ES6 classes.
Issues:
No static properties in ES6 classes
Models need to be init'ed to perform normalization etc
Models need a way to be connected to an active sequelize instance
Would break instanceof Sequelize.Model, so we might need an interface check inself.
Should instances be directly initiated from a model via new User()? Would be more semantic.
// models/user.jsclassUserextendsSequelize.Model{staticattributes(){return[// ...];}// Class methodsstaticfindByEmail(email){returnthis.findOne();}// Instance methodsverifyPassword(password){}}// models/index.jsimportUserfrom'./user';importsequelizefrom'./sequelize-instance';// Need some way to attach the model to a sequelize instance, specifically while allowing multiple attachments. Also need to run an sequelize init script on the model to normalize attributes etc.User=sequelize.import(User);// ?
Internally this need to be implemented for how extends is done under the hood in babel etc, so prototype inheritance.
Reacted by Byungjin Park (Claud), Dan Prince, Gert-Jan Vercauteren, Sofia Vicedomini, Brian Kilpatrick, Zava, Luke Tanner, François-Xavier Thoorens, Juan Camilo Varela López, Colin Harris and 7 more
Reacted by Julien Nakache, Abhishek Hingnikar, Alexandre Paré, Mina Luke, James Billingham, Ifemide, Zava and Rigo B Castro
sequelize.import=function(Model){classModelFactoryextendsModel{constructor(...args){super(...args);//forward all arguments to original constructor//_connect inherited from Sequelize.Modelthis._connect(sequelize);}}returnModelFactory;}
That way newUser instanceof UserModel and newUser instanceof Sequelize.Model remains true, too.
Need to figure out how to test this. We won't be using babel just yet internally, so it will be vanilla JS. But id like to test it with a babel compiled file class.
@mickhansen I totally agree, that's not a solution for ES6 class. Angular 2 try to solve the problem (they massively use decorators) by providing solution for ES5/6. We could have a look.
It provides validation decorators for properties of a Class (Required, Pattern, Min, Max etc) and then has adapters for exporting the meta data into Angular2 FormBuilder instances, MongooseSchemas etc. Think it's brilliant and would really like to use Interfaces/Types.
Doctrine uses annotations for decorating PHP Classes and am loving it. Random example of Class Table Inheritance:
I recently tried to write a module that allows to use decorators and model classes in TypeScript with Sequelize 3, but I did not succeed. I was going for a syntax like this:
The extends is necessary because the class needs to inherit all the methods like save(). But it is not possible, because in the typings Model is defined as an interface, not an abstract class. The underlying problem here is that Instances are not actually intances of Models. If this was changed then we could use real classes that are properly typed. The current way of passing classMethods, instanceMethods, getterMethods and setterMethods is bad because TypeScript cannot know about the presence of these methods on the Model/Instances, so you have to duplicate them by writing them in an interface aswell.
User.build() instanceof User should be true, and User.build() should be the same as new User().
sequelize.define() would be a class factory and not do
@jonjaques Well the classes you define are not actually the Models you use later, so a bit pointless imo. I just implemented the first major step towards an ES6-class-based Sequelize API in #5924.
@mickhansen@janmeier Now that #5924 is finished we could discuss how to improve the API. In the optimal case, Model.init() should not be needed. The only things one would have to assign on the model would be
attributes
options
connection
Actually, they should all be optional (connection is only the default connection and can alternatively be passed to methods as an options).
Is it possible to completely remove init()?
Also, new Model() should work like Model.build(), all logic needs to be moved from build() into the constructor (which already takes the same arguments, but apparently doesn't do some validation that build() does). Should Model.build() be removed/deprecated? There would still be bulkBuild() of course.
@felixfbecker Of course, however it does significantly improve the readability and definition of said models, especially with decorators. I guess I was just commenting that if we could get something close to that API it would be great. Sounds like thats the case in #5924. 😄
@intellix My approach goes a little bit further. It provides some more decorators. Decorators for model-relations, which makes it more intuitive to create associations, separate decorators for validation and some more… And yes, the defined classes are the actually used models. So that userInstance instanceof User will be true.
sequelize-typescript does only work - as the name implies - with typescript, but supports sequelize version 3 and version 4. So it can be used from now with the latest stable sequelize version. https://github.com/RobinBuschmann/sequelize-typescript
@RobinBuschmann Imo () => Model is super hacky. It only works because TS transpiles the reference to import_1.Model. This will not work with ES6 modules, only CommonJS output. I also think you should mention that your classes wrap the real sequelize, e.g. you have enormous amounts of code handling delegation to Sequelize methods, preparing options, copying methods etc.
@felixfbecker thanks for your feedback. But I think you're wrong when saying, that () => Model will not work with native es6 modules. It will work, because es6 modules should be able to handle circular dependencies. Can you provide something, that says the opposite?
What do you mean with I should mention, that my classes wrap the real sequelize?
For the rest you're right, for sequelize version 3 there are some adjustments and code delegations necessary. But most of the functionality is achieved by simple prototypal inheritance and I think it is worth the effort. Regarding version 4, there is nearly nothing adjusted to get it to work.
notice how it's a_1.A, not A (it's the CommonJS exports object of a.js). If you didn't use a function, a_1.A would be undefined at declaration time, but when the function is called, the a_1 object was updated with the exported A.
Afaik ES6 imports do not work like that, the import works more like this:
const{ A }=require('./a')__decorate(classB{},{'a': HasMany(()=>A)})
A is undefined at the time of importing it, and it will be undefined forever.
If you have any proof in the spec that this is not the case, please share, because I still don't know the one best way to do ORM models with decorators.
This is all very theoretical, since there is no final specification of how es-modules should be loaded. But all articles I've found (not official: altereos.com, medium.com, ...) saying it would be possible to do it like that.
At least I mostly believe in Guy Bedfords system.js. Since its es-module-loader implementation tries to follow the whatwg specification as much as possible. When assuming that loading es modules will work like this
Activity
corbanb commentedon Oct 26, 2015
💯
novacrazy commentedon Oct 27, 2015
Would a pseudo-factory pattern work well for connecting it to the sequelize instance?
Example:
where
importis something like:That way
newUser instanceof UserModelandnewUser instanceof Sequelize.Modelremains true, too.mickhansen commentedon Oct 27, 2015
@novacrazy I was thinking something along those lines yes.
mickhansen commentedon Oct 27, 2015
Need to figure out how to test this. We won't be using babel just yet internally, so it will be vanilla JS. But id like to test it with a babel compiled file class.
kripod commentedon Dec 24, 2015
I think that this should definitely be a milestone for v4 😄
verdier commentedon Jan 14, 2016
@mickhansen I totally agree, that's not a solution for ES6 class. Angular 2 try to solve the problem (they massively use decorators) by providing solution for ES5/6. We could have a look.
EDIT: see #5205
verdier commentedon Jan 14, 2016
And, has said before, there is nothing to change to have a beautiful support for decorators through plugin. So that's not the discussion.
verdier commentedon Jan 14, 2016
@mickhansen what's the problem with the
ModelFactoryit allows to have options before theclassbody and also to inherit fromSequelize.Model.mickhansen commentedon Jan 14, 2016
@verdier It just doesn't seem very idiomatic, but i don't feel strongly about it either way at the moment.
intellix commentedon Mar 26, 2016
There were a few people talking about using Decorators in another thread. Just wanted to add that I think Decorators here would be awesome. If you want an idea of how it would look then checkout this repository: https://github.com/martinmcwhorter/modelmetadata
It provides validation decorators for properties of a Class (Required, Pattern, Min, Max etc) and then has adapters for exporting the meta data into Angular2 FormBuilder instances, MongooseSchemas etc. Think it's brilliant and would really like to use Interfaces/Types.
Doctrine uses annotations for decorating PHP Classes and am loving it. Random example of Class Table Inheritance:
Decorator spec: https://github.com/wycats/javascript-decorators/blob/master/README.md
Babel plugin to parse them: https://babeljs.io/docs/plugins/syntax-decorators/
felixfbecker commentedon May 11, 2016
I recently tried to write a module that allows to use decorators and model classes in TypeScript with Sequelize 3, but I did not succeed. I was going for a syntax like this:
The
extendsis necessary because the class needs to inherit all the methods likesave(). But it is not possible, because in the typingsModelis defined as an interface, not an abstract class. The underlying problem here is that Instances are not actually intances of Models. If this was changed then we could use real classes that are properly typed. The current way of passingclassMethods,instanceMethods,getterMethodsandsetterMethodsis bad because TypeScript cannot know about the presence of these methods on the Model/Instances, so you have to duplicate them by writing them in an interface aswell.User.build() instanceof Usershould be true, andUser.build()should be the same asnew User().sequelize.define()would be a class factory and not doanymore, but instead
so in ES5 something like
mickhansen commentedon May 12, 2016
@felixfbecker Yeah, want to do something like that for 4.0
jonjaques commentedon May 26, 2016
Though the documentation is lacking, this module works pretty well for my purposes:
https://github.com/ConciergeAuctions/sequelize-classes
Would be interested to see what sequelize devs think of this.
felixfbecker commentedon May 26, 2016
@jonjaques Well the classes you define are not actually the Models you use later, so a bit pointless imo. I just implemented the first major step towards an ES6-class-based Sequelize API in #5924.
felixfbecker commentedon May 26, 2016
@mickhansen @janmeier Now that #5924 is finished we could discuss how to improve the API. In the optimal case,
Model.init()should not be needed. The only things one would have to assign on the model would beattributesoptionsconnectionActually, they should all be optional (
connectionis only the default connection and can alternatively be passed to methods as an options).Is it possible to completely remove
init()?Also,
new Model()should work likeModel.build(), all logic needs to be moved frombuild()into the constructor (which already takes the same arguments, but apparently doesn't do some validation thatbuild()does). ShouldModel.build()be removed/deprecated? There would still bebulkBuild()of course.jonjaques commentedon May 26, 2016
@felixfbecker Of course, however it does significantly improve the readability and definition of said models, especially with decorators. I guess I was just commenting that if we could get something close to that API it would be great. Sounds like thats the case in #5924. 😄
mickhansen commentedon May 30, 2016
@felixfbecker build should be deprecated yes, possibly removed.
optionsas an object or individual keys.felixfbecker commentedon Aug 28, 2016
@intellix proof of concept for decorators with v4.0.0-1 https://www.npmjs.com/package/sequelize-decorators
RobinBuschmann commentedon Mar 17, 2017
@intellix My approach goes a little bit further. It provides some more decorators. Decorators for model-relations, which makes it more intuitive to create associations, separate decorators for validation and some more… And yes, the defined classes are the actually used models. So that
userInstance instanceof Userwill be true.sequelize-typescript does only work - as the name implies - with typescript, but supports sequelize version 3 and version 4. So it can be used from now with the latest stable sequelize version. https://github.com/RobinBuschmann/sequelize-typescript
felixfbecker commentedon Mar 21, 2017
@RobinBuschmann Imo
() => Modelis super hacky. It only works because TS transpiles the reference toimport_1.Model. This will not work with ES6 modules, only CommonJS output. I also think you should mention that your classes wrap the real sequelize, e.g. you have enormous amounts of code handling delegation to Sequelize methods, preparing options, copying methods etc.RobinBuschmann commentedon Mar 21, 2017
@felixfbecker thanks for your feedback. But I think you're wrong when saying, that
() => Modelwill not work with native es6 modules. It will work, because es6 modules should be able to handle circular dependencies. Can you provide something, that says the opposite?What do you mean with I should mention, that my classes wrap the real sequelize?
For the rest you're right, for sequelize version 3 there are some adjustments and code delegations necessary. But most of the functionality is achieved by simple prototypal inheritance and I think it is worth the effort. Regarding version 4, there is nearly nothing adjusted to get it to work.
felixfbecker commentedon Mar 21, 2017
Afaik it handles circular dependencies in the way that if you
b.ts can already get a reference of A because it has already been exported. But you do
The reason it works with TS is that TS transpiles roughly to this:
notice how it's
a_1.A, notA(it's the CommonJSexportsobject ofa.js). If you didn't use a function,a_1.Awould be undefined at declaration time, but when the function is called, thea_1object was updated with the exportedA.Afaik ES6 imports do not work like that, the import works more like this:
Ais undefined at the time of importing it, and it will beundefinedforever.If you have any proof in the spec that this is not the case, please share, because I still don't know the one best way to do ORM models with decorators.
RobinBuschmann commentedon Mar 21, 2017
This is all very theoretical, since there is no final specification of how es-modules should be loaded. But all articles I've found (not official: altereos.com, medium.com, ...) saying it would be possible to do it like that.
At least I mostly believe in Guy Bedfords system.js. Since its es-module-loader implementation tries to follow the whatwg specification as much as possible. When assuming that loading es modules will work like this
...the
() => Modelapproach will work as well.I do understand, what you're trying to say. But it isn't said, that import/export will work internally like this:
Or do you have some proof in the spec for that?
Nevertheless, decorators are experimental as well. So I see no conclusion unless a specification for both is finalized ;)