A module to extend Loopback built-in Model (User, AccessToken, etc.) without creating new Model. ModelExtender loads Model definition synchronously.
- Extend built-in model definition:
acl
hidden
mixins
options
properties
-
relations
(Polymorphic and HasAndBelongsToMany is not supported yet) - Datasource-related options (e.g.
mysql
)
Steps below is an example to extend User
model:
- Create model file
user-x.js
anduser-x.json
incommon/models
folder. - Write only attributes to be extended in
user-x.json
such as mapping model to MySQL table, add properties, add relations, etc. No need to rewrite what already defined inUser
model, unless you need it:{ "mysql": { "table": "user" }, "properties": { "emailVerified": { "type": "boolean", "mysql": { "columnName": "email_verified", "dataType": "smallint", "dataLength": null, "dataPrecision": 1, "dataScale": 0, "nullable": "N" } }, "verificationToken": { "type": "string", "mysql": { "columnName": "verification_token", "dataType": "smallint", "dataLength": null, "dataPrecision": 1, "dataScale": 0, "nullable": "Y" } }, "createdAt": { "type": "Date", "required": false, "mysql": { "columnName": "created_at", "dataType": "datetime", "nullable": "N" } }, "updatedAt": { "type": "Date", "required": false, "mysqlz": { "columnName": "updated_at", "dataType": "datetime", "nullable": "N" } } }, "mixin": { "Controller": true }, "relations": { "customer": { "type": "hasOne", "model": "Customer", "foreignKey": "customerId" }, } }
- Write extended methods in
user-x.js
file.module.exports = User => { const say = User.say = (userId, message) => { console.log('User %d said %s', userId, message) } User.prototype.say = function(message) => { let userId = this.id say(userId, message) } }
- Call
modelExtender.extend
inserver/boot/init.js
boot script.const modelExtender = require('loopback-model-extender') module.exports = app => { modelExtender.extend(app, {models: 'User'}) }
- [ ] Add support for extending Polymorphic and HasAndBelongsToMany relation
- [ ] API documentation
- [ ] Write test
- Saggaf Arsyad saggaf@nusantarabetastudio.com