Models in the Node.js ORM, Sequelize, can be expanded with both class level and instance level functions. This video will show you how to extend your models to add helpers or business logic, and explain the methods execution scope.
Sequelize supports adding class and instance functions to models via the define method's options argument. Class methods are accessed from the model's definition object. I have an author model already set up. If I add a class method to it called "foo," it will be accessible by calling author.foo. Instance methods are accessed from an instance of the model.
If I have an author instance, perhaps from assigning the result of calling author.build to the variable Mike, I'd be able to call the instance method bar by invoking Mike.bar.
Let's take a look at some examples. We'll start with class methods.
To add a class method to my model, I'll need to add an object as the third argument to define and specify a classMethods property, which is also an object. Each property key of the classMethods object specifies the name of the method that will be added to the class.
If I add a property called "foo" here, it'll be accessible as author.foo. I'm going to name this one "buildFromArgs." The property value is the function that will be executed when the class method is invoked. There are no standard arguments, so I can add whatever I'd like.
The function will execute under the context of the model definition, which means I have access to my author model via the "this" keyword. Executing under the model definitions context allows you to easily reuse the functions in many models without having to duplicate them.
My buildFromArgs class method is just going to build and return a new instance of author from the given arguments. Now, I'm going to call the buildFromArgs function from the author object and assign it to the variable Mike. When I log the result, the unsaved object is printed to the screen.
Next, let's take a look at instance methods. Like class methods, instance methods are added to the options argument of the define method in a property called "instanceMethods." Just like class methods, each property key of the instanceMethods object will specify the name of the method that will be added to the instance.
The property value is the function that will be executed when the instance method is invoked. The upperCaseAndSave instance method I've just added to author will force the value of the specified field to upper case, then call save on the instance.
It's worth pointing out that instance methods run under the context of the instance they are called from. When I call Mike.upperCaseAndSave, the "this" keyword will refer to the author instance Mike. When run and logged, the output now has an ID indicating that the data has been saved and the last name has been forced to upper case.