0.0.1 • Published 5 years ago

@danieldietrich/object-builder v0.0.1

Weekly downloads
-
License
MIT
Repository
github
Last release
5 years ago

npm versionvulnerabilitiesminzipped size   buildcoverage   Platform   Sponsordonatelicense   Follow

object-builder

A generic functional object builder for TypeScript.

Builders guide the user through the construction process of possibly complex object types. Take advantage of TypeScript's type system and model your domain wisely!

Please consider to directly use an object literal {} instead, if possible. Keep it simple!

Features:

  • one generic builder that covers all existing object types
  • dynamically build deep object structures
  • provide default attributes
  • set multiple attributes at once
  • set attributes in arbitrary order

Installation

npm i @danieldietrich/object-builder

Usage

The module supports ES6 import and CommonJS require style.

Basic example

import builder from '@danieldietrich/object-builder';

type Person = {
    forename: string
    surname: string
}

const personBuilder = builder<Person>({ defaultValues: { forename: "Daniel", surname: "" }});

const daniel = personBuilder.with({ surname: "Dietrich" }).build();

Result:

{
    forename: 'Daniel',  // default value of person builder
    surname: 'Dietrich'  // manually set
}

Example with nested objects

import builder from '@danieldietrich/object-builder';

type Person = {
    forename: string
    surname: string
    phone?: number
    address?: Address[]
}

type Address = {
    street?: string
    zip?: number
    city?: string
    country?: 'foo' | 'bar' | 'baz'
}

const personBuilder = builder<Person>({ defaultValues: { forename: "(unknown)", surname: "(unknown)" }});
const addressBuilder = builder<Address>({ defaultValues: {}});

// inferred type: Person
const daniel = personBuilder
    .with({ forename: 'Daniel', surname: 'Dietrich' })
    .with({ phone: 123 })
    .with({ address: [
        addressBuilder.with({ street: 'Milkyway', country: 'foo' }).build(),
        addressBuilder.with({ street: 'Elmstreet', country: 'bar' }).build()
    ]})
    .build();

Result:

{
    forename: 'Daniel',
    surname: 'Dietrich',
    phone: 123,
    address: [
        { street: 'Milkyway', country: 'foo' },
        { street: 'Elmstreet', country: 'bar' }
    ]
}

Options

OptionDescription
defaultValuesAn object containing default values, at least for all required properties

Copyright © 2020 by Daniel Dietrich. Released under the MIT license.