Skip to content

Instantly share code, notes, and snippets.

@stuartwakefield
Last active January 20, 2016 13:59
Show Gist options
  • Save stuartwakefield/70cc41ef5edbfcf99cbf to your computer and use it in GitHub Desktop.
Save stuartwakefield/70cc41ef5edbfcf99cbf to your computer and use it in GitHub Desktop.
Pattern for refable entities
/**
* I represent a domain entity within the
* system called "entry". I have a $ref
* property which is a unique identifier
* that can be used to address me.
*/
class Entry {
constructor(data) {
this._$ref = EntryRef.from(data.$ref);
// Other properties
}
get $ref() {
return this._$ref;
}
}
/**
* I represent a reference to an "entry"
* domain entity within the system. I
* can be used to indicate which "entry"
* an operation should be performed on.
* I am a value object.
*/
class EntryRef {
constructor(value) {
this._$ref = value;
}
get $ref() {
return this._$ref;
}
toString() {
return this._$ref;
}
valueOf() {
return this._$ref;
}
static from(value) {
return value instanceof EntryRef ?
value : value.$ref instanceof EntryRef ?
value.$ref : new EntryRef(value.$ref ?
value.$ref : value);
}
}
function acceptsRefableEntry(refable) {
var ref = EntryRef.from(refable);
// Do stuff with ref
}
// All of the following are analogous
acceptsRefableEntry('http://example.com/entries/abc123');
acceptsRefableEntry(new EntryRef('http://example.com/entries/abc123'));
acceptsRefableEntry(new Entry({
$ref: 'http://example.com/entries/abc123'
}));
acceptsRefableEntry(new Entry({
$ref: new EntryRef('http://example.com/entries/abc123')
}));
acceptsRefableEntry(new Entry({
$ref: new Entry({
$ref: 'http://example.com/entries/abc123'
})
}));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment