@@ -10,6 +10,11 @@ import {
1010 isEvaluationSuccessResponse ,
1111 isBulkEvaluationFailureResponse ,
1212 isBulkEvaluationSuccessResponse ,
13+ EvaluationFailureErrorCode ,
14+ OFREPApiEvaluationFailureResult ,
15+ OFREPApiBulkEvaluationFailureResult ,
16+ EvaluationSuccessResponse ,
17+ EvaluationFlagValue ,
1318} from '../model' ;
1419import {
1520 OFREPApiFetchError ,
@@ -18,6 +23,15 @@ import {
1823 OFREPApiUnauthorizedError ,
1924 OFREPForbiddenError ,
2025} from './errors' ;
26+ import {
27+ FlagMetadata ,
28+ FlagNotFoundError ,
29+ GeneralError ,
30+ InvalidContextError ,
31+ ParseError ,
32+ TargetingKeyMissingError ,
33+ ResolutionDetails ,
34+ } from '@openfeature/core' ;
2135
2236export type FetchAPI = WindowOrWorkerGlobalScope [ 'fetch' ] ;
2337export type RequestOptions = Omit < RequestInit , 'method' | 'body' > ;
@@ -117,3 +131,45 @@ export class OFREPApi {
117131 throw new OFREPApiUnexpectedResponseError ( response , 'The OFREP response does not match the expected format' ) ;
118132 }
119133}
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