dml icon indicating copy to clipboard operation
dml copied to clipboard

Formatting Support ?

Open 1fabiopereira opened this issue 8 years ago • 3 comments

A feature that I deem useful and can be added in future versions if following the purpose of this library is the possibility of passing a formatting function to the field, for example:

sample.model

/*
 * An example data model
 */

Date created
Number id

String name {
  required true // this is a comment
  gt 2 "Must be greater than 2 characters"
  lte 256 "Must be less than or equal to 256 characters"
  formatter  (str)=> str.toUpperCase()
}

String bio "A bio must be a string" {
  lte 140 "A bio must fit into a tweet"
}

Boolean accountType
}

index.js

const Models = require('node-dml')

let model = Models.compile(fs.readFileSync('sample.model', 'utf8'))

let result = model({
  id: 1337,
  created: new Date(),
  name: 'Glen Danzig',
  accountType: 'awesome'
})

Output

{
  data: {
    id: 1337,
    created: '2016-10-02T13:56:44.931Z',
    name: 'GLEN DANZIG', // Formatted in uppercase
    accountType: 'awesome'
  },
  length: 1,
  rules: {
    accountType: [{
      validator: 'type',
      message: 'Expected type [Boolean] but got type [String]'
    }]
  }
}

1fabiopereira avatar Jan 17 '17 19:01 1fabiopereira

I like that idea, a pull request would certainly be welcome. It might be tough to find the end of the javascript or parse properly. Another option though, is adding a plugin system, which could be pretty cool. then we could npm install various advanced validators. i had something like this in the back of my mind while i was originally writing this version. this code might help make a plugin system reasonable to implement.

heapwolf avatar Jan 17 '17 21:01 heapwolf

Perfect I'll study your code and see how it works in the background because to be honest I got lost sometimes in it and as much as possible I can check which better option the plugin or add directly to the lib

1fabiopereira avatar Jan 17 '17 21:01 1fabiopereira

How did you imagine this system of plugins ?

1fabiopereira avatar Jan 17 '17 22:01 1fabiopereira