Modélico
  • Introduction
  • Quick start
    • Types
    • Metadata
    • Nested types example
    • Immutability
  • Basics
    • Optional / null values
    • Deep operations: getIn and setIn
    • Custom serialisation
  • Advanced
    • JSON validation
    • Reviving polymorphic JSON
    • Proxies
  • Recipes
    • ES5 classes
    • Runtime type for subclasses
    • Reviving large arrays in batches
Powered by GitBook
On this page

Quick start

Modélico's goal is to parse JSON strings like

{
  "name": "Robbie"
}

into JavaScript custom objects so that we can do things like this:

const myPet = M.fromJSON(Animal, petJson)

myPet.speak() // => 'my name is Robbie!'

Here is how Animal would look like:

const M = require('modelico')

class Animal extends M.createModel(m => ({
  name: m.string()
})) {
  speak() {
    const name = this.name()

    return (name === '') ? `I don't have a name` : `My name is ${name}!`
  }
}
const M = require('modelico')
const Ajv = require('ajv')

class Animal extends M.createAjvModel(new Ajv(), m => ({
  name: m.string({minLength: 1})
})) {
  speak () {
    const name = this.name()

    // the validation is only applied when reviving, not when creating new
    // instances directly (ie. new Animal({name: ''})) does not throw
    return (name === '') ? `I don't have a name` : `My name is ${name}!`
  }
}

Now when can do the following to get the schema:

M.getSchema(Animal);
// =>
// {
//   "type": "object",
//   "properties": {
//     "name": {
//       "$ref": "#/definitions/2"
//     }
//   },
//   "required": ["name"],
//   "definitions": {
//     "2": {
//       "type": "string",
//       "minLength": 1
//     }
//   }
// }
PreviousIntroductionNextTypes

Last updated 4 years ago

The name is required by default. See the to change the default behaviour.

With a bit more effort, we can have a detailed JSON schema, with the benefits that they bring, eg. integration with to generate random data.

See the to learn more.

Optional / null values page
JSON Shema Faker
nested types example