Enhance Your Loopback Models with Custom mixins
Read the full article on Sicara’s blog here.
Loopback provides a very high-level javascript framework for your backend: prebuilt methods, tables, data validation, routes, etc. Unfortunately its comprehensive documentation is not easy to follow. You will likely miss some part of it and end up re-doing things. With pain.
In this post I want to put light on the very useful mixins option of your model.json
declaration file.
Mixins overview
Several models of your application are likely to share common properties, relations, methods, etc. For instance, you may want to add a timestamp or a userstamp to each one your records. Or you want to add computed properties to your model.
Loopback mixins let you factorize any of these actions on models. In other words, any things that you want to define on a model (properties, relations, acl, methods, hooks, etc.) can be defined in a mixin.
Load prebuilt Loopback mixins
You can find on internet prebuilt mixins like for instance the loopback-ds-timestamp-mixin that add the createdAt
and updatedAt
fields to your model:
- first install the mixin:
npm i loopback-ds-timestamp-mixin --save
- then add the mixins property to your
server/model-config.json
:
{
"_meta": {
"sources": [
"loopback/common/models",
"loopback/server/models",
"../common/models",
"./models"
],
"mixins": [
"loopback/common/mixins",
"../node_modules/loopback-ds-timestamp-mixin",
"../common/mixins"
]
}
}
- finally in your
model.json
file, add:
{
"mixins": {
"TimeStamp": true
}
}
Unfortunately there is not a lot of public mixins availables. Fortunately I am going to tell you how to create your own!
Create your own mixin
Public mixins are useful but to harness the power of mixins you will need to create a custom one fitted to your special case.
… Read the full article on Sicara’s blog here.