A set of tools to use within your AdonisJS models
Install npm module:
$ adonis install adonis-model-utilities
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'
]
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'})
}
}
class UserSchema extends Schema {
up () {
this.create('users', (table) => {
table.uuid('id').index().unique().notNullable()
})
}
down () {
this.drop('users')
}
}
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'})
}
}
/** @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
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"
{
prefix: "formatted", //defaul model attribute prefix like formattedValue
symbol : "US$ ", // default currency symbol is '$'
format: "%s%v", // controls output: %s = symbol, %v = value/number (can be object: see below)
decimal : ",", // decimal point separator
thousand: ".", // thousands separator
precision : 2 // decimal places
}
Add trait to the model and set the fields that should be formatted:
class User {
static super () {
super.boot()
/**
* Format date trait
*/
this.addTrait('@provider:IgorTrinidad/FormatDate', {fields: ['bday'], unformatted: 'YYYY-MM-DD',formatted: 'DD/MM/YYYY'})
}
}
{
fields: ['bday'],
unformatted: 'YYYY-MM-DD', //*optional
formatted: 'DD/MM/YYYY', //*optional
setter: true, //*optional
getter: true //*optional
}
You can set the trait to only apply the getter, setter or both to the field before save on the db or fetch the data
This trait shouldn't be used on created_at and updated_at columns or dates setted using AdonisJS dates mutator
Add trait to the model and set the field that should be TitleCase:
class User {
static super () {
super.boot()
/**
* Title case
*/
this.addTrait('@provider:IgorTrinidad/TitleCase', { fields: ['firstName', 'lastName'] })
}
}
this trait apply a setter on defined fields so all fields will be saved with Title Case (first char uppercase for each word of the string)
Add trait to the model and set the trait options:
class User {
static super () {
super.boot()
/**
* FullName trait
*/
this.addTrait('@provider:IgorTrinidad/FullName', {
fullName: 'fullName',
firstName: 'firstName',
lastName: 'lastName'
})
}
}
Add trait to the model and set the field that should be ParseNumber:
class User {
static super () {
super.boot()
/**
* Parse Number
*/
this.addTrait('@provider:IgorTrinidad/ParseNumber', { fields: ['value_one', 'value_two'] })
}
}
this trait apply a getter on defined fields to parse numbers, this may be necessary if your db engine are formating number columns with too much zero decimals as string
git clone https://github.com/igortrinidad/adonis-model-utilities.git
npm install
DB=sqlite node japa-tests
git clone https://github.com/igortrinidad/adonis-model-utilities.git
cd adonis-model-utilities/example
npm install
adonis key:generate
adonis test
adonis test
- Igor Trindade - Developer
- github.com/igortrinidad
- https://igortrindade.dev
This project is licensed under the MIT License - see the LICENSE file for details.
- v1.2.3
- Initial release.
- Added model attribute prefix option for formatCurrency
- Added functional tests using Japa Tests
- Abstracted titleCase map function
- Added FullName trait
- Breaking changes: simplified all traits options inside trait function, changed UuidHook to trait, removed getters from models
- Fixed missing dependencies on PasswordTrait and FormatDate