Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@jaysalvat/smart-model

Package Overview
Dependencies
Maintainers
1
Versions
31
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@jaysalvat/smart-model

Javascript object model

  • 0.3.3
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
5
increased by400%
Maintainers
1
Weekly downloads
 
Created
Source
 ________  _____ ______   ________  ________  _________  _____ ______   ________  ________  _______   ___          
|\   ____\|\   _ \  _   \|\   __  \|\   __  \|\___   ___\\   _ \  _   \|\   __  \|\   ___ \|\  ___ \ |\  \         
\ \  \___|\ \  \\\__\ \  \ \  \|\  \ \  \|\  \|___ \  \_\ \  \\\__\ \  \ \  \|\  \ \  \_|\ \ \   __/|\ \  \        
 \ \_____  \ \  \\|__| \  \ \   __  \ \   _  _\   \ \  \ \ \  \\|__| \  \ \  \\\  \ \  \ \\ \ \  \_|/_\ \  \       
  \|____|\  \ \  \    \ \  \ \  \ \  \ \  \\  \|   \ \  \ \ \  \    \ \  \ \  \\\  \ \  \_\\ \ \  \_|\ \ \  \____  
    ____\_\  \ \__\    \ \__\ \__\ \__\ \__\\ _\    \ \__\ \ \__\    \ \__\ \_______\ \_______\ \_______\ \_______\
   |\_________\|__|     \|__|\|__|\|__|\|__|\|__|    \|__|  \|__|     \|__|\|_______|\|_______|\|_______|\|_______|
   \|_________|                                                                                                    

npm version

SmartModel

Javascript object model.

  • 1Kb+ gzipped
  • Value transformation
  • Value format
  • Value type validation
  • Value content validation (required, custom rules)
  • Default value
  • Readonly properties
  • Virtual property
  • Throw exception (or not) if invalid
  • Nested models
  • Live cycle events
  • Proper documentation ^^

Works on modern browsers. Check if tests pass on your browser.

Install

Provided formats are IFFE, ESM, CJS and UMD, all minified.

NPM

npm install @jaysalvat/smart-model
import SmartModel from '@jaysalvat/smart-model'

Module from CDN

import SmartModel from 'https://unpkg.com/@jaysalvat/smart-model@latest/build/smart-model.esm.min.js'

The old way

<script src="https://unpkg.com/@jaysalvat/smart-model@latest/build/smart-model.min.js"></script>

Usage

Better documentation soon...

function readingtime(text) { /*...*/ }

const Post = SmartModel.create('Post', {
    title: {
      required: true,
      type: String,
    },
    body: {
      required: true,
      type: String,
      rule: {
        'tooShort': (calue) => value.length < 100,
        'tooLong': (calue) => value.length > 1000,
      }
    },
    createdAt: {
      type: Date,
      default: new Date(),
      transform: (value) => new Date(value),
      format: (value) => value.toLocaleString()
    },
    updatedAt: {
      type: Date,
      default: new Date(),
      transform: (value) => new Date(value),
      format: (value) => value.toLocaleString()
    },
    // Nested model
    author: {
      required: true,
      type: {
        firstname: {
          required: true,
          type: String
        },
        lastname: {
          type: String
        }
      }
    },
    // Virtual properties
    bodyLength: (post) => post.body.length, 
    readingTime: (post) => readingTime(post.body)
  }, 
  // Settings
  {
    strict: false,
    exceptions: true
  }
  // Events
  {
    onUpdate() {
      this.updatedAt = new Date()
    }
  }
)
const post = new Post({
  title: 'My new post',
  body: 'Lorem ipsum...',
  author: {
    firstname: 'Brad',
    lastname: 'Pitt'
  }
})

Documentation

Schema

Options for property:

OptionTypeDescription
typeanyThe required type () of a value. You can set a schema or another model () in order to nest models
requiredboolThe value is required. See settings.empty for the empty check function
readonlyboolThe value can't be overwritten
defaultanyThe default value if the property is undefined
transformfnA function to transform the value to set
formatfnA function to format the value to get
ruleobjectAn object which contains the validation rules (**)
[*] Type

Type can be String, Boolean, Number, Date, Function or a class. If a schema is set as a type, a nested model will be created.

const Post = SmartModel.create('Post', {
  title: { 
    type: String 
  },
  body: { 
    type: String 
  },
  Date: { 
    type: Date 
  },
  author: {
    type {
      firstname: {
        type: String
      },
      lastnaame: {
        type: String
      }
    }
  }
})

An existing Model can be set as a type in order to nest this Model.

const Author = SmartModel.create('Author', {
  firstname: {
    type: String
  },
  lastnaame: {
    type: String
  }
})

const Post = SmartModel.create('Post', {
  title: { 
    type: String 
  },
  body: { 
    type: String 
  },
  Date: { 
    type: Date 
  },
  body: { 
    type: string 
  },
  author: {
    type: Author
  }
})
[**]s Rule

Multiple rules of validation can be set on a property.

const Discount = SmartModel.create('Discount', {
  percent: {
    type: Number,
    rule: {
      'min': {value) => value < 0,
      'max': {value) => value > 100
    }
  }
})

Settings

OptionTypeDefaultDescription
strictboolfalseAllow to set property not present in the schema
emptyfnfn (***)Function to check if a value is empty if required
exceptionsbool/objectobject (****)Throw exceptions on errors. can be boolean or òbject` for advanced settings
[***] Empty check function

The default function to check if a value is empty is:

(value) => value === '' || value === null || value === undefined
[****] Exceptions object
OptionTypeDefault
readonlyboolfalse
requiredbooltrue
rulebooltrue
strictboolfalse
typebooltrue

Methods

$put
const article = new Article()

article.put({
  title: 'My article',

})
$patch

Same as $put, but only passed property are updated.

$eject
const article = new Article()

const json = article.eject()

Custom methods

Methods can be added to models.

const Article = SmartModel.create('Article', {
  body: {
    type: String
  }
}, {}, {
  excerpt(limit = 10) {
    return this.body.substr(0, limit) + '…'
  }
})

Callbacks

Models have some callbacks methods that are called when properties are set, get, updated or deleted.

const User = SmartModel.create('User', {
  username: {
    type: String
  }
}, {}, {
  $onBeforeGet() {}
  $onBeforeSet() {}
  $onBeforeUpdate() {}
  $onDelete() {}
  $onGet() {}
  $onBeforeDelete() {}
  $onSet() {}
  $onUpdate() {}
})

Dev

Dev mode

npm run dev

Build

npm run build

Lint

npm run lint

Fix lint errors

npm run lint:fix

Tests

npm run test
npm run test:watch
npm run test:browser

Bump version and publish to NPM

npm run release
npm run release:patch
npm run release:minor
npm run release:major

Keywords

FAQs

Package last updated on 23 Feb 2021

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc