Skip to content

ES6 class support #4728

Closed
Closed

Description

@mickhansen

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.js
class User extends Sequelize.Model {
  static attributes() {
    return [
      // ...
    ];
  }

  // Class methods
  static findByEmail(email) {
    return this.findOne();
  }

  // Instance methods
  verifyPassword(password) {

  }
}

// models/index.js
import User from './user';
import sequelize from './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.

Activity

  1. added
    type: feature
    on Oct 25, 2015
  2. corbanb commented on Oct 26, 2015

    @corbanb

    💯

  3. novacrazy commented on Oct 27, 2015

    @novacrazy

    Would a pseudo-factory pattern work well for connecting it to the sequelize instance?

    Example:

    // models/user.js
    export default class UserModel extends Sequelize.Model {
    // ...
    }
    
    // models/index.js
    import UserModel from './user';
    import sequelize from './sequelize-instance';
    
    export const User = sequelize.import(UserModel);
    
    // somefile.js
    import {User} from 'models/index.js';
    
    let newUser = new User({name: 'username', email: '[email protected]'});

    where import is something like:

    sequelize.import = function(Model) {
        class ModelFactory extends Model {
            constructor(...args) {
                super(...args); //forward all arguments to original constructor
    
                //_connect inherited from Sequelize.Model
                this._connect(sequelize);
            }
        }
    
        return ModelFactory;
    }

    That way newUser instanceof UserModel and newUser instanceof Sequelize.Model remains true, too.

  4. mickhansen commented on Oct 27, 2015

    @mickhansen
    ContributorAuthor

    @novacrazy I was thinking something along those lines yes.

  5. mickhansen commented on Oct 27, 2015

    @mickhansen
    ContributorAuthor

    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.

  6. kripod commented on Dec 24, 2015

    @kripod

    I think that this should definitely be a milestone for v4 😄

  7. added this to the 4.0 milestone on Jan 13, 2016
  8. verdier commented on Jan 14, 2016

    @verdier
    Contributor

    @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

  9. verdier commented on Jan 14, 2016

    @verdier
    Contributor

    And, has said before, there is nothing to change to have a beautiful support for decorators through plugin. So that's not the discussion.

  10. verdier commented on Jan 14, 2016

    @verdier
    Contributor

    @mickhansen what's the problem with the ModelFactory it allows to have options before the class body and also to inherit from Sequelize.Model.

  11. mickhansen commented on Jan 14, 2016

    @mickhansen
    ContributorAuthor

    @verdier It just doesn't seem very idiomatic, but i don't feel strongly about it either way at the moment.

  12. intellix commented on Mar 26, 2016

    @intellix

    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:

    @Model({
      underscored: true,
      timestamps: true
    })
    abstract class GameEvent {
    
        @Column({
            type: SequelizeDate,
            field: 'start_time',
            required: true
        })
        startTime: Date;
    
        @Column({
            type: SequelizeDate,
            field: 'end_time',
            required: true
        })
        endTime: Date;
    
        construct() {
            this.startTime = new Date;
        }
    }
    
    @Model()
    class Movement extends GameEvent {
    
        @HasOne({
            required: true
        })
        mapSquare: MapSquare;
    }

    Decorator spec: https://github.com/wycats/javascript-decorators/blob/master/README.md
    Babel plugin to parse them: https://babeljs.io/docs/plugins/syntax-decorators/

  13. felixfbecker commented on May 11, 2016

    @felixfbecker
    Contributor

    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:

    @Table({
      tableName: 'users',
      underscored: true
    })
    class User extends Sequelize.Model {
    
      @Column({type: Sequelize.STRING, primaryKey: true})
      public username: string
    
      public get accessor() {}
      public set accessor(v) {}
    
      public static staticMethod() {}
    
      public method() {}
    }

    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

    return new Model()

    anymore, but instead

    return class extends Model {}

    so in ES5 something like

    var NewModel = function() {
      Model.call(this)
    }
    NewModel.prototype = Object.create(Model.prototype)
    NewModel.prototype.constructor = NewModel
    if (Object.setPrototypeOf) {
      Object.setPrototypeOf(NewModel, Model)
    } else {
      NewModel.__proto__ = Model
    }
    NewModel.options = options
    return NewModel
  14. mickhansen commented on May 12, 2016

    @mickhansen
    ContributorAuthor

    @felixfbecker Yeah, want to do something like that for 4.0

  15. jonjaques commented on May 26, 2016

    @jonjaques

    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.

  16. felixfbecker commented on May 26, 2016

    @felixfbecker
    Contributor

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

  17. felixfbecker commented on May 26, 2016

    @felixfbecker
    Contributor

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

  18. jonjaques commented on May 26, 2016

    @jonjaques

    @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. 😄

  19. mickhansen commented on May 30, 2016

    @mickhansen
    ContributorAuthor

    @felixfbecker build should be deprecated yes, possibly removed.

    options as an object or individual keys.

  20. felixfbecker commented on Aug 28, 2016

    @felixfbecker
    Contributor
  21. RobinBuschmann commented on Mar 17, 2017

    @RobinBuschmann
    Member

    @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

  22. felixfbecker commented on Mar 21, 2017

    @felixfbecker
    Contributor

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

  23. RobinBuschmann commented on Mar 21, 2017

    @RobinBuschmann
    Member

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

  24. felixfbecker commented on Mar 21, 2017

    @felixfbecker
    Contributor

    Afaik it handles circular dependencies in the way that if you

    • export A in a.ts
    • import B in a.ts from b.ts
    • import A in b.ts from a.ts
    • export B in b.ts

    b.ts can already get a reference of A because it has already been exported. But you do

    • import B in a.ts from b.ts
    • import A in b.ts from a.ts ❗️ Error, because A is not exported yet
    • use A in an arrow function while declaring B in b.ts
    • export B in b.ts
    • use B in an arrow function while declaring A in a.ts
    • export A in a.ts

    The reason it works with TS is that TS transpiles roughly to this:

    const a_1 = require('./a')
    __decorate(class B {}, {
      'a': HasMany(() => a_1.A)
    })

    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(class B {}, {
      '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.

  25. RobinBuschmann commented on Mar 21, 2017

    @RobinBuschmann
    Member

    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

    (function(System, SystemJS) {System.register(['./b'], function(exports_1, context_1) {
        "use strict";
        var __moduleName = context_1 && context_1.id;
        var b_1;
        function a() {
            return b_1.b();
        }
        exports_1("a", a);
        function a1() {
            return 'a1';
        }
        exports_1("a1", a1);
        return {
            setters:[
                function (b_1_1) {
                    b_1 = b_1_1;
                }],
            execute: function() {
            }
        }
    });
    
    })(System, System);

    ...the () => Model approach 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:

    const { A } = require('./a')
    __decorate(class B {}, {
      'a': HasMany(() => A)
    })

    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 ;)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    type: feature

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions