🚀 Socket Launch Week Day 5:Introducing Repository Access Permissions and Custom Roles.Learn more
Sign In

@mkrause/constructor

Package Overview
Dependencies
Maintainers
1
Versions
3
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@mkrause/constructor

Create JavaScript constructors using declarative schema definitions.

latest
Source
npmnpm
Version
1.0.2
Version published
Weekly downloads
7
-69.57%
Maintainers
1
Weekly downloads
 
Created
Source

constructor.js

Utility library to create JavaScript constructors based on a declarative schema.

Usage:

Example:

    import constructor from '@mkrause/constructor';
    
    const MyConstructor = constructor({ x: String, y: Number });
    const myInstance = MyConstructor({ x: "foo", y: 42 });
    myInstance instanceof MyConstructor; // true
    
    MyConstructor({ x: "foo", y: "42" }); // Throws `InvalidInstanceException`

Each instance stores the validated value in a property accessed through a special symbol constructor.internal:

    const Person = constructor({ name: String, score: Number });
    const john = Person({ name: "John", score: 101 });
    
    john[constructor.internal]; // { name: "John", score: 101 }

This internal property is not supposed to be accessed by the consumer directly. Instead, a constructor should specify a public API through extend():

    const Person = constructor({ name: String, score: Number })
        .extend({
            get name() { return this[constructor.internal].name; },
            get score() { return this[constructor.internal].score; },
        });
    
    const john = Person({ name: "John", score: 101 });
    john.name; // "John"

Any JS constructor can be used as type in a schema, including other constructors defined using constructor():

    const Post = constructor({ author: Person, submitted: Date });
    const post = Post({ author: john, submitted: new Date("2017-01-01") });

Similar libraries

  • https://github.com/molnarg/js-schema

FAQs

Package last updated on 16 Apr 2017

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