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

adonis-cast-attributes

v1.0.0

Published

Cast attributes in AdonisJS

Downloads

58

Readme

adonis-cast-attributes

Attributes sent to the server should be checked. This module allows you to cast data to its expected form before processing.

How to use

Install npm module:

$ adonis install adonis-cast-attributes

Register provider

Once you have installed adonis-cast-attributes, make sure to register the provider inside start/app.js in order to make use of it.

const providers = [
  'adonis-cast-attributes/providers/CastAttributesProvider'
]

Using the module:

Add trait and casts to the model:

class User {
  static super () {
    super.boot()
    
      // Add the trait and casts to a model
    this.addTrait('@provider:CastAttributes')
  }
  
  // add values to cast to upon set
  static get casts () {
    return {
      company_id: 'int',
      name: 'string',
      interests: 'array',
      another: 'string',
    }
  }
}

Add data to model from route:

const User = use('App/Models/User')

Route.post('/register', ({request}) => {
  const model = new User()
  model.fill({
    company_id: "321",
    interests: ['item1','item2','item3'],
    name: 'Simon',
    another: ['1','blah','2']
  })
  
  console.log(model)
  /*
    output:
    { company_id: 321,
      interests: [ 'item1', 'item2', 'item3' ],
      name: "Simon"
      another: "1,blah,2" }
    */
})

Now whatever gets posted from the client will abide by the cast rules. So company_id will be coerced to an interger, name to a string (meaning if an array or some other invalid data was passed it will convert) and interests to an array.

Nested casting

You can also pass in the 'shape' a nested object you wish to cast like so:

  // ... inside model class ...
  static get casts () {
    return {
      company_id: 'int',
      name: 'string',
      profile: {
        nickname: 'string',
        birthdate: 'date',
        age: 'int'
      }
    }
  }

Now when an tabulated data is sent such as profile[nickname]=simon&profile[birthdate]=1983-11-10&age=123 it will cast the nested data accordingly.

You can also pass in arrays:

  // ... inside model class ...
  static get casts () {
    return {
      company_id: 'int',
      name: 'string',
      properties: [{
        key: 'string',
        value: 'json',
      }]
    }
  }

Regardless of how many array values you post for properties it will abide by the first casted rule in the casts.properties array.

Casting options

The following cast types are available:

  • int,integer,real,float,double - Numbers
  • string - String
  • bool,boolean - Boolean
  • object,json - JSON
  • array - Array
  • date,datetime - Moment date object
  • timestamp - Unix timestamp

Manual attribute casting

You can use the AttributeCaster provider to manually cast data like so:

  const AttributeCaster = use('AttributeCaster')

  const values = {
    name: 'Simon',
    id: '321',
    interests: ['coding', 'sports', 'reading'],
    properties: [
      {key: 'color', value: 'red'},
      {key: 'last_ip', value: '123.123.123.123'},
      {key: 'last_login', value: [1,2,3]}
    ],
    another: '123',
    another2: 'testing',
  }

and then cast the values:

  const casts = {
    id: 'int',
    interests: 'array',
    properties: [{
      key: 'string',
      value: 'string'
    }]
  }
  
  console.log(AttributeCaster.castAttributes(casts, values))
  /*
  output:
  { name: 'Simon',
    id: 321,
    interests: [ 'coding', 'sports', 'reading' ],
    properties: 
     [ { key: 'color', value: 'red' },
       { key: 'last_ip', value: '123.123.123.123' },
       { key: 'last_login', value: '1,2,3' } ],
    another: '123',
    another2: 'testing' }
  */

or you can ignore values that don't have a cast type set:

  const casts = {
    id: 'int',
    interests: 'array',
    properties: [{
      key: 'string',
      value: 'string'
    }]
  }
  
  console.log(AttributeCaster.castAttributes(casts, values, true))
  /*
  output:
  { id: 321,
    interests: [ 'coding', 'sports', 'reading' ],
    properties: 
     [ { key: 'color', value: 'red' },
       { key: 'last_ip', value: '123.123.123.123' },
       { key: 'last_login', value: '1,2,3' } ] }
  */

or fill in missing casts when value wasn't passed:

  const casts = {
    team_id: 'int',
    registered_date: 'datetime',
    last_name: 'string',
    id: 'int',
    interests: 'array',
    properties: [{
      key: 'string',
      value: 'string'
    }]
  }
  
  console.log(AttributeCaster.castAttributes(casts, values, false, false))
  /*
  output:
  { team_id: 0,
    registered_date: null,
    last_name: '',
    id: 321,
    interests: [ 'coding', 'sports', 'reading' ],
    properties: 
     [ { key: 'color', value: 'red' },
       { key: 'last_ip', value: '123.123.123.123' },
       { key: 'last_login', value: '1,2,3' } ],
    name: 'Simon',
    another: '123',
    another2: 'testing' }
  */

Built With

Versioning

SemVer is used for versioning. For the versions available, see the tags on this repository.

Authors

License

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

Changelog

  • v1.0.0
    • Initial release.