Skip to content
This repository was archived by the owner on Jul 1, 2024. It is now read-only.

Commit 59f4504

Browse files
committed
sdk/evaluateBatch: add "reject on any failure" option
Signed-off-by: Stephan Renatus <[email protected]>
1 parent 8806581 commit 59f4504

File tree

2 files changed

+34
-11
lines changed

2 files changed

+34
-11
lines changed

src/opaclient.ts

+14-11
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ export interface RequestOptions<Res> extends FetchOptions {
4646
* evaluateBatch method.
4747
*/
4848
export interface BatchRequestOptions<Res> extends RequestOptions<Res> {
49-
failAny?: boolean; // TODO
49+
rejectErrors?: boolean; // reject promise if any of the batch results errored
5050
}
5151

5252
/** OPAClient is the starting point for using the high-level API.
@@ -166,23 +166,26 @@ export class OPAClient {
166166
const res = resp.batchMixedResults || resp.batchSuccessfulPolicyEvaluation;
167167
if (!res) throw `no result in API response`;
168168

169-
return Object.fromEntries(
170-
Object.entries(res.responses ?? {}).map(([k, v]) => [
171-
k,
172-
processResult(v, opts),
173-
]),
174-
);
169+
const entries = [];
170+
for (const [k, v] of Object.entries(res.responses ?? {})) {
171+
entries.push([k, await processResult(v, opts)]);
172+
}
173+
return Object.fromEntries(entries);
175174
}
176175
}
177176

178177
function processResult<Res>(
179178
res: ResponsesSuccessfulPolicyResponse | ServerError,
180-
opts?: RequestOptions<Res>,
181-
) {
182-
if (res && "code" in res) return res as ServerError;
179+
opts?: BatchRequestOptions<Res>,
180+
): Promise<Res | ServerError> {
181+
if (res && "code" in res) {
182+
if (opts?.rejectErrors) return Promise.reject(res as ServerError);
183+
184+
return Promise.resolve(res as ServerError);
185+
}
183186

184187
const fromResult = opts?.fromResult || id<Res>;
185-
return fromResult(res.result);
188+
return Promise.resolve(fromResult(res.result));
186189
}
187190

188191
function id<T>(x: any): T {

tests/authorizer.test.ts

+20
Original file line numberDiff line numberDiff line change
@@ -453,6 +453,26 @@ allow if {
453453
},
454454
});
455455
});
456+
457+
it("rejects mixed-mode result if instructed", async () => {
458+
assert.rejects(
459+
new OPAClient(serverURL).evaluateBatch(
460+
"condfail/p",
461+
{
462+
one: {
463+
a: "a",
464+
},
465+
two: {
466+
a: "a",
467+
b: "a",
468+
},
469+
},
470+
{
471+
rejectErrors: true,
472+
},
473+
),
474+
);
475+
});
456476
});
457477

458478
after(async () => {

0 commit comments

Comments
 (0)