README
adonis-model-utilities
A set of tools to use within your AdonisJS models
1. Install
Install npm module:
$ adonis install adonis-model-utilities
2. Register provider
Once you have installed adonis-model-utilities, make sure to register the provider inside start/app.js
in order to make use of it.
const providers = [
'adonis-model-utilities/providers/ModelUtilitiesProvider'
]
3. Use:
Uuid Trait:
Add trait to the model that will make a new model instance using node uuid
class User {
static super () {
super.boot()
/**
* Uuid trait
*/
this.addTrait('@provider:IgorTrinidad/Uuid', { field: 'id', version: 'v4'})
}
}
node uuid v4
string
This trait create an model instance with id v1, v3, v4 or v5
.
You can change the uuid version to Example of migration using Uuid Hook
class UserSchema extends Schema {
up () {
this.create('users', (table) => {
table.uuid('id').index().unique().notNullable()
})
}
down () {
this.drop('users')
}
}
Password Hash Trait:
Add trait to the model and set the field that should apply the Hash method of own Adonis framework:
class User {
static super () {
super.boot()
/**
* PasswordHash trait
*/
this.addTrait('@provider:IgorTrinidad/PasswordHash', {field: 'password'})
}
}
this model above is exactly same as:
/** @type {import('@adonisjs/framework/src/Hash')} */
const Hash = use('Hash')
class User extends Model {
static get hidden () {
return ['password']
}
static boot () {
super.boot()
/**
* A hook to hash the user password before saving
* it to the database.
*/
this.addHook('beforeSave', async (userInstance) => {
if (userInstance.dirty.password) {
userInstance.password = await Hash.make(userInstance.password)
}
})
}
}
module.exports = User
Format Currency Trait:
Add trait to the model and set the fields that should be formatted:
class Product {
static super () {
super.boot()
/**
* Format currency trait
*/
this.addTrait('@provider:IgorTrinidad/FormatCurrency', {fields: ['value'], prefix: 'formatted', symbol: 'US$ '})
}
}
This trait apply add computed property (virtual) for the model, not changing the original field with prefix "formatted" eg: formattedPrice: "R$ 105,45"
Trait options (*optional)
{
prefix: "formatted", //defaul model attribute prefix like formattedValue
symbol : "US$ ", // default currency symbol is '