value-object.js
Value Object
- objects that matter only as the combination of their
properties. Two value objects with the same values for all their properties are
considered equal.
This library provides a convenient way to define strict, immutable value objects
represented by ES6 classes.
Install
npm install value-object
Defining value objects
Use subclasses to define value objects with type constraints:
const ValueObject = require('value-object')
class Currency extends ValueObject.define({
code: 'string',
name: 'string'
}) {}
class Money extends ValueObject.define({
currency: Currency,
amount: 'number'
}) {}
Instantiating value objects
Use the new
keyword:
const gbp = new Currency({ code: 'GBP', name: 'British Pounds' })
const price = new Money({ currency: gbp, amount: 12.34 })
The type constraints prevent value objects from being instantiated with
incorrect arguments:
new Currency({ code: 'USD', name: 123 })
new Currency({ code: 'NZD', name: 'New Zealand Dollars', colour: 'All black' })
> new Money({ amount: 123 })
Equality
Value objects are considered to be equal if their properties are equal:
gbp.isEqualTo(new Currency({ code: 'GBP', name: 'British Pounds' }))
gbp.isEqualTo(new Currency({ code: 'EUR', name: 'Euros' }))
Creating new value objects from existing value objects
Use with(newAttributes)
to create new value objects
var salePrice = price.with({ amount: 12.00 })
salePrice.currency.code
Converting value objects to JSON
Use toJSON()
to create an object that can be passed to JSON.stringify()
JSON.stringify(gbp.toJSON())
Converting value objects from JSON
Use ValueObject.deserializeForNamespaces()
to create a deserialize function
that can turn the resulting JSON back into objects
const deserialize = ValueObject.deserializeForNamespaces([{ Currency }])
const gbp2 = deserialize('{"__type__":"Currency","code":"GBP","name":"British Pounds"}')
gbp2.isEqualTo(gbp)
Immutability
Value objects cannot be updated. Use strict mode:
to throw errors when attempts to set property values are made.
gbp.code = 'USD'