@@ -10,6 +10,11 @@ import {
10
10
isEvaluationSuccessResponse ,
11
11
isBulkEvaluationFailureResponse ,
12
12
isBulkEvaluationSuccessResponse ,
13
+ EvaluationFailureErrorCode ,
14
+ OFREPApiEvaluationFailureResult ,
15
+ OFREPApiBulkEvaluationFailureResult ,
16
+ EvaluationSuccessResponse ,
17
+ EvaluationFlagValue ,
13
18
} from '../model' ;
14
19
import {
15
20
OFREPApiFetchError ,
@@ -18,6 +23,15 @@ import {
18
23
OFREPApiUnauthorizedError ,
19
24
OFREPForbiddenError ,
20
25
} from './errors' ;
26
+ import {
27
+ FlagMetadata ,
28
+ FlagNotFoundError ,
29
+ GeneralError ,
30
+ InvalidContextError ,
31
+ ParseError ,
32
+ TargetingKeyMissingError ,
33
+ ResolutionDetails ,
34
+ } from '@openfeature/core' ;
21
35
22
36
export type FetchAPI = WindowOrWorkerGlobalScope [ 'fetch' ] ;
23
37
export type RequestOptions = Omit < RequestInit , 'method' | 'body' > ;
@@ -117,3 +131,45 @@ export class OFREPApi {
117
131
throw new OFREPApiUnexpectedResponseError ( response , 'The OFREP response does not match the expected format' ) ;
118
132
}
119
133
}
134
+
135
+ export function handleEvaluationError (
136
+ result : OFREPApiEvaluationFailureResult | OFREPApiBulkEvaluationFailureResult ,
137
+ ) : never {
138
+ const code = result . value . errorCode ;
139
+ const details = result . value . errorDetails ;
140
+
141
+ switch ( code ) {
142
+ case EvaluationFailureErrorCode . ParseError :
143
+ throw new ParseError ( details ) ;
144
+ case EvaluationFailureErrorCode . TargetingKeyMissing :
145
+ throw new TargetingKeyMissingError ( details ) ;
146
+ case EvaluationFailureErrorCode . InvalidContext :
147
+ throw new InvalidContextError ( details ) ;
148
+ case EvaluationFailureErrorCode . FlagNotFound :
149
+ throw new FlagNotFoundError ( details ) ;
150
+ case EvaluationFailureErrorCode . General :
151
+ throw new TargetingKeyMissingError ( details ) ;
152
+ default :
153
+ throw new GeneralError ( details ) ;
154
+ }
155
+ }
156
+
157
+ export function toResolutionDetails < T extends EvaluationFlagValue > (
158
+ result : EvaluationSuccessResponse ,
159
+ ) : ResolutionDetails < T > {
160
+ return {
161
+ value : result . value as T ,
162
+ variant : result . variant ,
163
+ reason : result . reason ,
164
+ flagMetadata : result . metadata && toFlagMetadata ( result . metadata ) ,
165
+ } ;
166
+ }
167
+
168
+ export function toFlagMetadata ( metadata : object ) : FlagMetadata {
169
+ // OFREP metadata is defined as any object but OF metadata is defined as Record<string, string | number | boolean>
170
+ const originalEntries = Object . entries ( metadata ) ;
171
+ const onlyPrimitiveEntries = originalEntries . filter ( ( [ , value ] ) =>
172
+ [ 'string' , 'number' , 'boolean' ] . includes ( typeof value ) ,
173
+ ) ;
174
+ return Object . fromEntries ( onlyPrimitiveEntries ) ;
175
+ }
0 commit comments