Skip to content

Commit daaff36

Browse files
committed
live-elements-web-server: Added ValueOrError class.
1 parent 514a235 commit daaff36

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
import StandardError from "../errors/standard-error.mjs";
2+
3+
export default class ValueOrError{
4+
constructor(value, error){
5+
this._value = value
6+
this._error = error
7+
}
8+
9+
get value(){ return this._value }
10+
get error(){ return this._error }
11+
12+
get hasValue(){ return this._value !== undefined }
13+
get hasError(){ return this._error !== undefined }
14+
15+
unwrapOrThrow(){
16+
if ( this._error ){
17+
throw this._error
18+
}
19+
return this._value
20+
}
21+
22+
unwrapAnd(cb){
23+
if ( this._error ){
24+
cb(this._error)
25+
}
26+
return this._value
27+
}
28+
29+
toJSON(valueCb, errorCb){
30+
if ( this._value ){
31+
return valueCb
32+
? { value: valueCb(this._value ) }
33+
: { value: this._value }
34+
} else {
35+
return errorCb
36+
? { error: errorCb(this._error) }
37+
: { error: this._error instanceof StandardError ? this._error.toJSON() : this._error.message }
38+
}
39+
}
40+
41+
static errorObject(error){
42+
return { error: error instanceof StandardError ? error.toJSON() : error.message }
43+
}
44+
static valueObject(value){
45+
return { value: value }
46+
}
47+
48+
static fromError(error){
49+
return new ValueOrError(undefined, error)
50+
}
51+
static fromValue(value){
52+
return new ValueOrError(value, undefined)
53+
}
54+
55+
static fromJSON(ob, valueCb, errorCb){
56+
if ( ob.hasOwnProperty('value') ){
57+
return valueCb
58+
? new ValueOrError(valueCb(ob.value))
59+
: new ValueOrError(ob.value)
60+
} else if ( ob.hasOwnProperty('error') ){
61+
return errorCb
62+
? new ValueOrError(undefined, errorCb(ob.error))
63+
: new ValueOrError(undefined, ob.error)
64+
}
65+
return new ValueOrError(undefined, new Error('ValueOrError: Object missing value or error key.'))
66+
}
67+
}

0 commit comments

Comments
 (0)