npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@igortrindade/adonis-model-utilities

v1.2.6

Published

A set of tools to use within AdonisJS models

Downloads

16

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'})
  }

}
This trait create an model instance with id node uuid v4 string
You can change the uuid version to v1, v3, v4 or v5.

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 '$'
    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
  }

Format Date Trait:

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'})
  }
  

}
Trait options (*optional)
  {
    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

Title Case Trait:

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)

FullName Trait:

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'
    })
  }

}
this trait apply a setter to the column formating the fullName for the on saving

Parse Number Trait:

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

Built With

Test functional (using Japa Tests)

  git clone https://github.com/igortrinidad/adonis-model-utilities.git
  npm install
  DB=sqlite node japa-tests

Test Adonis integration

  git clone https://github.com/igortrinidad/adonis-model-utilities.git
  cd adonis-model-utilities/example
  npm install
  adonis key:generate
  adonis test
  adonis test

Author

License

This project is licensed under the MIT License - see the LICENSE file for details.

Changelog

  • 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