Giter VIP home page Giter VIP logo

implement.js's Introduction

Implement.js npm version js-standard-style

  • Create interfaces to enforce, remove, or rename properties of objects
  • Use in testing to easily verify object shapes and property types
  • Effortlessly and safely parse API responses by renaming or removing properties
  • Errors and warnings are suppressed when process.env.NODE_ENV === 'production'

Docs

What is Implement.js?

Implement.js is a library that attempts to bring interfaces to JavaScript in the form of runtime type-checking.

Simply define an interface using Interface and call implement on an object to check if it implements the given interface.

const Hello = {
    greeting: 'hello',
    wave () {}
}
const Introduction = Interface('Introduction')({
    greeting: type('string'),
    handshake: type('function')
}, { error: true })

const HelloIntroduction = implement(Introduction)(Hello) // throws an error!

Setup

Install

yarn add implement-js

Build

yarn build

API

Implement

Accepts an Interface and an object, then checks to see if the object implements the given Interface.

implement(Interface)(object) -> object
Implementing classes

Since class is just a constructor function waiting to be called and not truly an object, we cannot check if it implements a given Interface. Also, due to the dynamic nature of class properties, even once instantiated we cannot reliably implement interfaces against them.

Interface

Takes a string to be used as a name, if none is provided it generates a uuid, returns a function that accepts an object where all the keys are type objects, and returns an Interface. The Interface is to be used by implement.

Interface([name])(object[, options]) -> Interface object
Options
{
    // when true, errors and warnings are triggered when properties
    // other than those on the Interface are found, is suppressed if
    // trim is set to true - default: false
    strict: true,

    // remove methods that don’t match the Interface - default: false
    trim: true,

    // throws an error when Interface isn’t implemented - default: false
    error: true,

    // warns when Interface isn’t implemented - default: true
    warn: false,

    // accepts an Interface to extend, the new Interface must also
    // implement the extended Interface
    extend: Interface,

    // accepts an object where all property values are strings used to
    // rename the corresponding properties on the given object
    rename: { seats: 'chairs' }
}

Type

Accepts a string matching any JavaScript types, plus ‘array’ and 'any'.

If ‘array’ is passed, a second argument can be passed denoting the type of the elements of the array, if none is passed then the types of the elements will not be checked. The second argument should be an array containing type objects.

If ‘object’ is passed, a second argument can be passed containing an Interface for the object, if none is passed then the properties of the object will not be checked. The second argument should be an Interface.

type(string[, Array<type>|Interface]) -> Type

ES6 Modules / CommonJS

// ES6
import implement, { Interface, type } from 'implement-js'

// CommonJS modules
const implementjs = require('implement-js')
const implement = implementjs.default
const { Interface, type } = implementjs

Examples

Standard usage
import implement, { Interface, type } from 'implement-js'

const Passenger = Interface('Passenger')({
    name: type('string'),
    height: type('number')
})

const ChildPassenger = Interface('ChildPassenger')({
    hasBabySeat: type('boolean')
}, {
    extend: Passenger
})

const Car = Interface('Car')({
    speed: type('number'),
    passengers: type('array', [type('object', Passenger), type('object', ChildPassenger)]),
    beep: type('function')
}, { error: true })

// Successful implementation
const MyCar = implement(Car)({
    speed: 0,
    passengers: [],
    beep () {}
})

// Bad implementation - does not implement the beep method
const AnotherCar = implement(Car)({
    speed: 0,
    passengers: []
})
Unit tests
import implement from 'implement-js'
import CarService from '../services/CarService'
import { Vehicle } from '../Interfaces'

describe('CarService', () => {
    describe('getCar', () => {
        it('should implement the Vehicle Interface', done => {
            const someCar = CarService.getCar()

            // Ensure someCar implements Vehicle Interface
            implement(Vehicle)(someCar)

            done()
        })
    })
})
Renaming and refactoring API responses:
import { fetchUsers } from '../services/userService'
import implement, { Interface, type } from 'implement-js'

const User = Interface('User')({
    name: type('string'),
    id: type('number')
}, { trim: true })

const Users = Interface('Users')({
    users: type('array', [type('object', User)])
}, {
    trim: true,
    rename: { API_RESPONSE_USERS_LIST: 'users' }
})

const updateUsers = () => async dispatch => {
    dispatch(updateUsersBegin())

    try {
        const users = await fetchUsers()
        const MyUsers = implement(Users)(users)

        dispatch(updateUsersSuccess(MyUsers))
    } catch (err) {
        dispatch(updateUsersError(err))
    }
}

Code Style

eslint-config-standard

js-standard-style

implement.js's People

Contributors

jahans3 avatar dependabot[bot] avatar tmikaeld avatar

Watchers

James Cloos avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.