-
Notifications
You must be signed in to change notification settings - Fork 13
/
client.ts
769 lines (694 loc) · 34.9 KB
/
client.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
/**
* JavaScript and Node.js SDK for OpenFGA
*
* API version: 1.x
* Website: https://openfga.dev
* Documentation: https://openfga.dev/docs
* Support: https://openfga.dev/community
* License: [Apache-2.0](https://github.com/openfga/js-sdk/blob/main/LICENSE)
*
* NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT.
*/
import { AxiosResponse, AxiosInstance } from "axios";
import asyncPool = require("tiny-async-pool");
import { OpenFgaApi } from "./api";
import {
Assertion,
CheckRequest,
CheckRequestTupleKey,
CheckResponse,
ConsistencyPreference,
CreateStoreRequest,
CreateStoreResponse,
ExpandRequestTupleKey,
ExpandResponse,
GetStoreResponse,
ListObjectsRequest,
ListObjectsResponse,
ListStoresResponse,
ListUsersRequest,
ListUsersResponse,
ReadAssertionsResponse,
ReadAuthorizationModelResponse,
ReadAuthorizationModelsResponse,
ReadChangesResponse,
ReadRequest,
ReadRequestTupleKey,
ReadResponse,
TupleKey,
TupleKeyWithoutCondition,
WriteAuthorizationModelRequest,
WriteAuthorizationModelResponse,
WriteRequest,
} from "./apiModel";
import { BaseAPI } from "./base";
import { CallResult, PromiseResult } from "./common";
import { Configuration, RetryParams, UserConfigurationParams } from "./configuration";
import { FgaApiAuthenticationError, FgaRequiredParamError, FgaValidationError } from "./errors";
import {
chunkArray,
generateRandomIdWithNonUniqueFallback,
setHeaderIfNotSet,
} from "./utils";
import { isWellFormedUlidString } from "./validation";
export type UserClientConfigurationParams = UserConfigurationParams & {
storeId?: string;
authorizationModelId?: string;
}
export class ClientConfiguration extends Configuration {
/**
* provide storeId
*
* @type {string}
* @memberof ClientConfiguration
*/
storeId?: string;
/**
* provide authorizationModelId
*
* @type {string}
* @memberof ClientConfiguration
*/
authorizationModelId?: string;
constructor(params: UserClientConfigurationParams = {} as unknown as UserConfigurationParams) {
super(params);
this.storeId = params.storeId!;
this.authorizationModelId = params.authorizationModelId!;
}
public isValid(): boolean {
super.isValid();
if (this.storeId && !isWellFormedUlidString(this.storeId)) {
throw new FgaValidationError("storeId", "storeId must be in ULID format");
}
if (this.authorizationModelId && !isWellFormedUlidString(this.authorizationModelId)) {
throw new FgaValidationError("authorizationModelId", "authorizationModelId must be in ULID format");
}
return true;
}
}
const DEFAULT_MAX_METHOD_PARALLEL_REQS = 10;
const CLIENT_METHOD_HEADER = "X-OpenFGA-Client-Method";
const CLIENT_BULK_REQUEST_ID_HEADER = "X-OpenFGA-Client-Bulk-Request-Id";
export interface ClientRequestOpts {
retryParams?: RetryParams;
headers?: Record<string, string>;
}
export interface StoreIdOpts {
storeId?: string;
}
export interface AuthorizationModelIdOpts {
authorizationModelId?: string;
}
export interface ConsistencyOpts {
consistency?: ConsistencyPreference
}
export type ClientRequestOptsWithStoreId = ClientRequestOpts & StoreIdOpts;
export type ClientRequestOptsWithAuthZModelId = ClientRequestOpts & StoreIdOpts & AuthorizationModelIdOpts;
export type ClientRequestOptsWithConsistency = ClientRequestOpts & StoreIdOpts & AuthorizationModelIdOpts & ConsistencyOpts;
export type PaginationOptions = { pageSize?: number, continuationToken?: string; };
export type ClientCheckRequest = CheckRequestTupleKey &
Pick<CheckRequest, "context"> &
{ contextualTuples?: Array<TupleKey> };
export type ClientBatchCheckRequest = ClientCheckRequest[];
export type ClientBatchCheckSingleResponse = {
_request: ClientCheckRequest;
} & ({
allowed: boolean;
$response: AxiosResponse<CheckResponse>;
} | {
allowed: undefined;
error: Error;
});
export interface ClientBatchCheckResponse {
responses: ClientBatchCheckSingleResponse[];
}
export interface ClientWriteRequestOpts {
transaction?: {
disable?: boolean;
maxPerChunk?: number;
maxParallelRequests?: number;
}
}
export interface BatchCheckRequestOpts {
maxParallelRequests?: number;
}
export interface ClientWriteRequest {
writes?: TupleKey[];
deletes?: TupleKeyWithoutCondition[];
}
export enum ClientWriteStatus {
SUCCESS = "success",
FAILURE = "failure",
}
export interface ClientWriteSingleResponse {
tuple_key: TupleKey;
status: ClientWriteStatus;
err?: Error;
}
export interface ClientWriteResponse {
writes: ClientWriteSingleResponse[];
deletes: ClientWriteSingleResponse[];
}
export interface ClientListRelationsResponse {
relations: string[];
}
export interface ClientReadChangesRequest {
type: string;
}
export type ClientExpandRequest = ExpandRequestTupleKey;
export type ClientReadRequest = ReadRequestTupleKey;
export type ClientListObjectsRequest = Omit<ListObjectsRequest, "authorization_model_id" | "contextual_tuples" | "consistency"> & {
contextualTuples?: Array<TupleKey>
};
export type ClientListUsersRequest = Omit<ListUsersRequest, "authorization_model_id" | "contextual_tuples" | "consistency"> & {
contextualTuples?: Array<TupleKey>
};
export type ClientListRelationsRequest = Omit<ClientCheckRequest, "relation" | "consistency"> & {
relations?: string[],
};
export type ClientWriteAssertionsRequest = (CheckRequestTupleKey & Pick<Assertion, "expectation">)[];
export class OpenFgaClient extends BaseAPI {
public api: OpenFgaApi;
public authorizationModelId?: string;
public storeId?: string;
protected configuration: ClientConfiguration;
constructor(configuration: ClientConfiguration | UserClientConfigurationParams, protected axios?: AxiosInstance) {
super(configuration, axios);
if (configuration instanceof ClientConfiguration) {
this.configuration = configuration;
} else {
this.configuration = new ClientConfiguration(configuration);
}
this.configuration.isValid();
this.api = new OpenFgaApi(this.configuration, axios);
this.storeId = configuration.storeId;
this.authorizationModelId = configuration.authorizationModelId;
}
protected getStoreId(options: StoreIdOpts = {}, isOptional: boolean = false): string | undefined {
const storeId = options?.storeId || this.storeId;
if (storeId && !isWellFormedUlidString(storeId)) {
throw new FgaValidationError("storeId", "storeId must be in ULID format");
}
if (!isOptional && !storeId) {
throw new FgaValidationError("storeId", "storeId is required");
}
return storeId;
}
protected getAuthorizationModelId(options: AuthorizationModelIdOpts = {}): string | undefined {
const authorizationModelId = options?.authorizationModelId || this.authorizationModelId;
if (authorizationModelId && !isWellFormedUlidString(authorizationModelId)) {
throw new FgaValidationError("authorizationModelId", "authorizationModelId must be in ULID format");
}
return authorizationModelId;
}
/**
* checkValidApiConnection - Ensures that the credentials are valid for calling the API
* If the authorization model id is available, this will attempt to get that model
* Otherwise this will attempt to get the latest authorization model
* @param {ClientRequestOptsWithAuthZModelId} [options]
* @param {string} [options.authorizationModelId] - Overrides the authorization model id in the configuration
* @param {object} [options.headers] - Custom headers to send alongside the request
* @param {object} [options.retryParams] - Override the retry parameters for this request
* @param {number} [options.retryParams.maxRetry] - Override the max number of retries on each API request
* @param {number} [options.retryParams.minWaitInMs] - Override the minimum wait before a retry is initiated
*/
public async checkValidApiConnection(options: ClientRequestOptsWithAuthZModelId = {}): Promise<void> {
if (this.getAuthorizationModelId(options)) {
await this.readAuthorizationModel(options);
} else {
await this.readLatestAuthorizationModel(options);
}
}
/**********
* Stores *
**********/
/**
* ListStores - Get a paginated list of stores.
* @summary List all stores
* @param {ClientRequestOpts & PaginationOptions} [options]
* @param {number} [options.pageSize]
* @param {string} [options.continuationToken]
* @param {object} [options.headers] - Custom headers to send alongside the request
* @param {object} [options.retryParams] - Override the retry parameters for this request
* @param {number} [options.retryParams.maxRetry] - Override the max number of retries on each API request
* @param {number} [options.retryParams.minWaitInMs] - Override the minimum wait before a retry is initiated
* @throws { FgaError }
*/
async listStores(options: ClientRequestOptsWithAuthZModelId & PaginationOptions = {}): PromiseResult<ListStoresResponse> {
return this.api.listStores(options.pageSize, options.continuationToken, options);
}
/**
* CreateStore - Initialize a store
* @param {CreateStoreRequest} body
* @param {ClientRequestOpts} [options]
* @param {object} [options.headers] - Custom headers to send alongside the request
* @param {object} [options.retryParams] - Override the retry parameters for this request
* @param {number} [options.retryParams.maxRetry] - Override the max number of retries on each API request
* @param {number} [options.retryParams.minWaitInMs] - Override the minimum wait before a retry is initiated
*/
async createStore(body: CreateStoreRequest, options: ClientRequestOpts = {}): PromiseResult<CreateStoreResponse> {
return this.api.createStore(body, options);
}
/**
* GetStore - Get information about the current store
* @param {ClientRequestOptsWithStoreId} [options]
* @param {object} [options.headers] - Custom headers to send alongside the request
* @param {object} [options.retryParams] - Override the retry parameters for this request
* @param {number} [options.retryParams.maxRetry] - Override the max number of retries on each API request
* @param {number} [options.retryParams.minWaitInMs] - Override the minimum wait before a retry is initiated
*/
async getStore(options: ClientRequestOptsWithStoreId = {}): PromiseResult<GetStoreResponse> {
return this.api.getStore(this.getStoreId(options)!, options);
}
/**
* DeleteStore - Delete a store
* @param {ClientRequestOptsWithStoreId} [options]
* @param {object} [options.headers] - Custom headers to send alongside the request
* @param {object} [options.retryParams] - Override the retry parameters for this request
* @param {number} [options.retryParams.maxRetry] - Override the max number of retries on each API request
* @param {number} [options.retryParams.minWaitInMs] - Override the minimum wait before a retry is initiated
*/
async deleteStore(options: ClientRequestOptsWithStoreId = {}): PromiseResult<void> {
return this.api.deleteStore(this.getStoreId(options)!, options);
}
/************************
* Authorization Models *
************************/
/**
* ReadAuthorizationModels - Read all authorization models
* @param {ClientRequestOpts & PaginationOptions} [options]
* @param {number} [options.pageSize]
* @param {string} [options.continuationToken]
* @param {object} [options.headers] - Custom headers to send alongside the request
* @param {object} [options.retryParams] - Override the retry parameters for this request
* @param {number} [options.retryParams.maxRetry] - Override the max number of retries on each API request
* @param {number} [options.retryParams.minWaitInMs] - Override the minimum wait before a retry is initiated
*/
async readAuthorizationModels(options: ClientRequestOptsWithStoreId & PaginationOptions = {}): PromiseResult<ReadAuthorizationModelsResponse> {
return this.api.readAuthorizationModels(this.getStoreId(options)!, options.pageSize, options.continuationToken, options);
}
/**
* WriteAuthorizationModel - Create a new version of the authorization model
* @param {WriteAuthorizationModelRequest} body
* @param {ClientRequestOptsWithStoreId} [options]
* @param {object} [options.headers] - Custom headers to send alongside the request
* @param {object} [options.retryParams] - Override the retry parameters for this request
* @param {number} [options.retryParams.maxRetry] - Override the max number of retries on each API request
* @param {number} [options.retryParams.minWaitInMs] - Override the minimum wait before a retry is initiated
*/
async writeAuthorizationModel(body: WriteAuthorizationModelRequest, options: ClientRequestOptsWithStoreId = {}): PromiseResult<WriteAuthorizationModelResponse> {
return this.api.writeAuthorizationModel(this.getStoreId(options)!, body, options);
}
/**
* ReadAuthorizationModel - Read the current authorization model
* @param {ClientRequestOptsWithAuthZModelId} [options]
* @param {string} [options.authorizationModelId] - Overrides the authorization model id in the configuration
* @param {object} [options.headers] - Custom headers to send alongside the request
* @param {object} [options.retryParams] - Override the retry parameters for this request
* @param {number} [options.retryParams.maxRetry] - Override the max number of retries on each API request
* @param {number} [options.retryParams.minWaitInMs] - Override the minimum wait before a retry is initiated
*/
async readAuthorizationModel(options: ClientRequestOptsWithAuthZModelId = {}): PromiseResult<ReadAuthorizationModelResponse> {
const authorizationModelId = this.getAuthorizationModelId(options);
if (!authorizationModelId) {
throw new FgaRequiredParamError("ClientConfiguration", "authorizationModelId");
}
return this.api.readAuthorizationModel(this.getStoreId(options)!, authorizationModelId, options);
}
/**
* ReadLatestAuthorizationModel - Read the latest authorization model for the current store
* @param {ClientRequestOpts} [options]
* @param {object} [options.headers] - Custom headers to send alongside the request
* @param {object} [options.retryParams] - Override the retry parameters for this request
* @param {number} [options.retryParams.maxRetry] - Override the max number of retries on each API request
* @param {number} [options.retryParams.minWaitInMs] - Override the minimum wait before a retry is initiated
*/
async readLatestAuthorizationModel(options: ClientRequestOpts = {}): PromiseResult<ReadAuthorizationModelResponse> {
const { headers = {} } = options;
setHeaderIfNotSet(headers, CLIENT_METHOD_HEADER, "ReadLatestAuthorizationModel");
const authorizationModelsResponse = await this.readAuthorizationModels({ ...options, pageSize: 1, headers });
const response = authorizationModelsResponse as any as CallResult<ReadAuthorizationModelResponse>;
response.authorization_model = authorizationModelsResponse.authorization_models?.[0];
delete (response as any).authorization_models;
return response;
}
/***********************
* Relationship Tuples *
***********************/
/**
* Read Changes - Read the list of historical relationship tuple writes and deletes
* @param {ClientReadChangesRequest} [body]
* @param {ClientRequestOpts & PaginationOptions} [options]
* @param {number} [options.pageSize]
* @param {string} [options.continuationToken]
* @param {object} [options.headers] - Custom headers to send alongside the request
* @param {object} [options.retryParams] - Override the retry parameters for this request
* @param {number} [options.retryParams.maxRetry] - Override the max number of retries on each API request
* @param {number} [options.retryParams.minWaitInMs] - Override the minimum wait before a retry is initiated
*/
async readChanges(body?: ClientReadChangesRequest, options: ClientRequestOptsWithStoreId & PaginationOptions = {}): PromiseResult<ReadChangesResponse> {
return this.api.readChanges(this.getStoreId(options)!, body?.type, options.pageSize, options.continuationToken, options);
}
/**
* Read - Read tuples previously written to the store (does not evaluate)
* @param {ClientReadRequest} body
* @param {ClientRequestOpts & PaginationOptions & ConsistencyOpts} [options]
* @param {number} [options.pageSize]
* @param {string} [options.continuationToken]
* @param {object} [options.headers] - Custom headers to send alongside the request
* @param {ConsistencyPreference} [options.consistency] - The consistency preference to use
* @param {object} [options.retryParams] - Override the retry parameters for this request
* @param {number} [options.retryParams.maxRetry] - Override the max number of retries on each API request
* @param {number} [options.retryParams.minWaitInMs] - Override the minimum wait before a retry is initiated
*/
async read(body: ClientReadRequest = {}, options: ClientRequestOptsWithStoreId & PaginationOptions & ConsistencyOpts = {}): PromiseResult<ReadResponse> {
const readRequest: ReadRequest = {
page_size: options.pageSize,
continuation_token: options.continuationToken,
consistency: options.consistency
};
if (body.user || body.object || body.relation) {
readRequest.tuple_key = body;
}
return this.api.read(this.getStoreId(options)!, readRequest, options);
}
/**
* Write - Create or delete relationship tuples
* @param {ClientWriteRequest} body
* @param {ClientRequestOptsWithAuthZModelId & ClientWriteRequestOpts} [options]
* @param {string} [options.authorizationModelId] - Overrides the authorization model id in the configuration
* @param {object} [options.transaction]
* @param {boolean} [options.transaction.disable] - Disables running the write in a transaction mode. Defaults to `false`
* @param {number} [options.transaction.maxPerChunk] - Max number of items to send in a single transaction chunk. Defaults to `1`
* @param {number} [options.transaction.maxParallelRequests] - Max requests to issue in parallel. Defaults to `10`
* @param {object} [options.headers] - Custom headers to send alongside the request
* @param {object} [options.retryParams] - Override the retry parameters for this request
* @param {number} [options.retryParams.maxRetry] - Override the max number of retries on each API request
* @param {number} [options.retryParams.minWaitInMs] - Override the minimum wait before a retry is initiated
*/
async write(body: ClientWriteRequest, options: ClientRequestOptsWithAuthZModelId & ClientWriteRequestOpts = {}): Promise<ClientWriteResponse> {
const { transaction = {}, headers = {} } = options;
const {
maxPerChunk = 1, // 1 has to be the default otherwise the chunks will be sent in transactions
maxParallelRequests = DEFAULT_MAX_METHOD_PARALLEL_REQS,
} = transaction;
const { writes, deletes } = body;
const authorizationModelId = this.getAuthorizationModelId(options);
if (!transaction?.disable) {
const apiBody: WriteRequest = {
authorization_model_id: authorizationModelId,
};
if (writes?.length) {
apiBody.writes = { tuple_keys: writes };
}
if (deletes?.length) {
apiBody.deletes = { tuple_keys: deletes };
}
await this.api.write(this.getStoreId(options)!, apiBody, options);
return {
writes: writes?.map(tuple => ({
tuple_key: tuple,
status: ClientWriteStatus.SUCCESS,
})) || [],
deletes: deletes?.map(tuple => ({
tuple_key: tuple,
status: ClientWriteStatus.SUCCESS,
})) || []
};
}
setHeaderIfNotSet(headers, CLIENT_METHOD_HEADER, "Write");
setHeaderIfNotSet(headers, CLIENT_BULK_REQUEST_ID_HEADER, generateRandomIdWithNonUniqueFallback());
const writeResponses: ClientWriteSingleResponse[][] = [];
if (writes?.length) {
for await (const singleChunkResponse of asyncPool(maxParallelRequests, chunkArray(writes, maxPerChunk),
(chunk) => this.writeTuples(chunk,{ ...options, headers, transaction: undefined }).catch(err => {
if (err instanceof FgaApiAuthenticationError) {
throw err;
}
return {
writes: chunk.map(tuple => ({
tuple_key: tuple,
status: ClientWriteStatus.FAILURE,
err,
})),
deletes: []
};
}))) {
writeResponses.push(singleChunkResponse.writes);
}
}
const deleteResponses: ClientWriteSingleResponse[][] = [];
if (deletes?.length) {
for await (const singleChunkResponse of asyncPool(maxParallelRequests, chunkArray(deletes, maxPerChunk),
(chunk) => this.deleteTuples(chunk, { ...options, headers, transaction: undefined }).catch(err => {
if (err instanceof FgaApiAuthenticationError) {
throw err;
}
return {
writes: [],
deletes: chunk.map(tuple => ({
tuple_key: tuple,
status: ClientWriteStatus.FAILURE,
err,
})),
};
}))) {
deleteResponses.push(singleChunkResponse.deletes);
}
}
return { writes: writeResponses.flat(), deletes: deleteResponses.flat() };
}
/**
* WriteTuples - Utility method to write tuples, wraps Write
* @param {TupleKey[]} tuples
* @param {ClientRequestOptsWithAuthZModelId & ClientWriteRequestOpts} [options]
* @param {string} [options.authorizationModelId] - Overrides the authorization model id in the configuration
* @param {object} [options.transaction]
* @param {boolean} [options.transaction.disable] - Disables running the write in a transaction mode. Defaults to `false`
* @param {number} [options.transaction.maxPerChunk] - Max number of items to send in a single transaction chunk. Defaults to `1`
* @param {number} [options.transaction.maxParallelRequests] - Max requests to issue in parallel. Defaults to `10`
* @param {object} [options.headers] - Custom headers to send alongside the request
* @param {object} [options.retryParams] - Override the retry parameters for this request
* @param {number} [options.retryParams.maxRetry] - Override the max number of retries on each API request
* @param {number} [options.retryParams.minWaitInMs] - Override the minimum wait before a retry is initiated
*/
async writeTuples(tuples: TupleKey[], options: ClientRequestOptsWithAuthZModelId & ClientWriteRequestOpts = {}): Promise<ClientWriteResponse> {
const { headers = {} } = options;
setHeaderIfNotSet(headers, CLIENT_METHOD_HEADER, "WriteTuples");
return this.write({ writes: tuples }, { ...options, headers });
}
/**
* DeleteTuples - Utility method to delete tuples, wraps Write
* @param {TupleKeyWithoutCondition[]} tuples
* @param {ClientRequestOptsWithAuthZModelId & ClientWriteRequestOpts} [options]
* @param {string} [options.authorizationModelId] - Overrides the authorization model id in the configuration
* @param {object} [options.transaction]
* @param {boolean} [options.transaction.disable] - Disables running the write in a transaction mode. Defaults to `false`
* @param {number} [options.transaction.maxPerChunk] - Max number of items to send in a single transaction chunk. Defaults to `1`
* @param {number} [options.transaction.maxParallelRequests] - Max requests to issue in parallel. Defaults to `10`
* @param {object} [options.headers] - Custom headers to send alongside the request
* @param {object} [options.retryParams] - Override the retry parameters for this request
* @param {number} [options.retryParams.maxRetry] - Override the max number of retries on each API request
* @param {number} [options.retryParams.minWaitInMs] - Override the minimum wait before a retry is initiated
*/
async deleteTuples(tuples: TupleKeyWithoutCondition[], options: ClientRequestOptsWithAuthZModelId & ClientWriteRequestOpts = {}): Promise<ClientWriteResponse> {
const { headers = {} } = options;
setHeaderIfNotSet(headers, CLIENT_METHOD_HEADER, "DeleteTuples");
return this.write({ deletes: tuples }, { ...options, headers });
}
/************************
* Relationship Queries *
************************/
/**
* Check - Check if a user has a particular relation with an object (evaluates)
* @param {ClientCheckRequest} body
* @param {ClientRequestOptsWithConsistency} [options]
* @param {string} [options.authorizationModelId] - Overrides the authorization model id in the configuration
* @param {object} [options.headers] - Custom headers to send alongside the request
* @param {ConsistencyPreference} [options.consistency] - The consistency preference to use
* @param {object} [options.retryParams] - Override the retry parameters for this request
* @param {number} [options.retryParams.maxRetry] - Override the max number of retries on each API request
* @param {number} [options.retryParams.minWaitInMs] - Override the minimum wait before a retry is initiated
*/
async check(body: ClientCheckRequest, options: ClientRequestOptsWithConsistency = {}): PromiseResult<CheckResponse> {
return this.api.check(this.getStoreId(options)!, {
tuple_key: {
user: body.user,
relation: body.relation,
object: body.object,
},
context: body.context,
contextual_tuples: { tuple_keys: body.contextualTuples || [] },
authorization_model_id: this.getAuthorizationModelId(options),
consistency: options.consistency
}, options);
}
/**
* BatchCheck - Run a set of checks (evaluates)
* @param {ClientBatchCheckRequest} body
* @param {ClientRequestOptsWithAuthZModelId & BatchCheckRequestOpts} [options]
* @param {number} [options.maxParallelRequests] - Max number of requests to issue in parallel. Defaults to `10`
* @param {string} [options.authorizationModelId] - Overrides the authorization model id in the configuration
* @param {object} [options.headers] - Custom headers to send alongside the request
* @param {object} [options.retryParams] - Override the retry parameters for this request
* @param {number} [options.retryParams.maxRetry] - Override the max number of retries on each API request
* @param {number} [options.retryParams.minWaitInMs] - Override the minimum wait before a retry is initiated
*/
async batchCheck(body: ClientBatchCheckRequest, options: ClientRequestOptsWithConsistency & BatchCheckRequestOpts = {}): Promise<ClientBatchCheckResponse> {
const { headers = {}, maxParallelRequests = DEFAULT_MAX_METHOD_PARALLEL_REQS } = options;
setHeaderIfNotSet(headers, CLIENT_METHOD_HEADER, "BatchCheck");
setHeaderIfNotSet(headers, CLIENT_BULK_REQUEST_ID_HEADER, generateRandomIdWithNonUniqueFallback());
const responses: ClientBatchCheckSingleResponse[] = [];
for await (const singleCheckResponse of asyncPool(maxParallelRequests, body, (tuple) => this.check(tuple, { ...options, headers })
.then(response => {
(response as ClientBatchCheckSingleResponse)._request = tuple;
return response as ClientBatchCheckSingleResponse;
})
.catch(err => {
if (err instanceof FgaApiAuthenticationError) {
throw err;
}
return {
allowed: undefined,
error: err,
_request: tuple,
};
})
)) {
responses.push(singleCheckResponse);
}
return { responses };
}
/**
* Expand - Expands the relationships in userset tree format (evaluates)
* @param {ClientExpandRequest} body
* @param {string} body.relation The relation
* @param {string} body.object The object, must be of the form: `<type>:<id>`
* @param {ClientRequestOptsWithConsistency} [options]
* @param {string} [options.authorizationModelId] - Overrides the authorization model id in the configuration
* @param {object} [options.headers] - Custom headers to send alongside the request
* @param {ConsistencyPreference} [options.consistency] - The consistency preference to use
* @param {object} [options.retryParams] - Override the retry parameters for this request
* @param {number} [options.retryParams.maxRetry] - Override the max number of retries on each API request
* @param {number} [options.retryParams.minWaitInMs] - Override the minimum wait before a retry is initiated
*/
async expand(body: ClientExpandRequest, options: ClientRequestOptsWithConsistency = {}): PromiseResult<ExpandResponse> {
return this.api.expand(this.getStoreId(options)!, {
authorization_model_id: this.getAuthorizationModelId(options),
tuple_key: body,
consistency: options.consistency
}, options);
}
/**
* ListObjects - List the objects of a particular type that the user has a certain relation to (evaluates)
* @param {ClientListObjectsRequest} body
* @param {ClientRequestOptsWithConsistency} [options]
* @param {string} [options.authorizationModelId] - Overrides the authorization model id in the configuration
* @param {object} [options.headers] - Custom headers to send alongside the request
* @param {ConsistencyPreference} [options.consistency] - The consistency preference to use
* @param {object} [options.retryParams] - Override the retry parameters for this request
* @param {number} [options.retryParams.maxRetry] - Override the max number of retries on each API request
* @param {number} [options.retryParams.minWaitInMs] - Override the minimum wait before a retry is initiated
*/
async listObjects(body: ClientListObjectsRequest, options: ClientRequestOptsWithConsistency = {}): PromiseResult<ListObjectsResponse> {
return this.api.listObjects(this.getStoreId(options)!, {
authorization_model_id: this.getAuthorizationModelId(options),
user: body.user,
relation: body.relation,
type: body.type,
context: body.context,
contextual_tuples: { tuple_keys: body.contextualTuples || [] },
consistency: options.consistency
}, options);
}
/**
* ListRelations - List all the relations a user has with an object (evaluates)
* @param {object} listRelationsRequest
* @param {string} listRelationsRequest.user The user object, must be of the form: `<type>:<id>`
* @param {string} listRelationsRequest.object The object, must be of the form: `<type>:<id>`
* @param {string[]} listRelationsRequest.relations The list of relations to check
* @param {TupleKey[]} listRelationsRequest.contextualTuples The contextual tuples to send
* @param {object} listRelationsRequest.context The contextual tuples to send
* @param options
*/
async listRelations(listRelationsRequest: ClientListRelationsRequest, options: ClientRequestOptsWithConsistency & BatchCheckRequestOpts = {}): Promise<ClientListRelationsResponse> {
const { user, object, relations, contextualTuples, context } = listRelationsRequest;
const { headers = {}, maxParallelRequests = DEFAULT_MAX_METHOD_PARALLEL_REQS } = options;
setHeaderIfNotSet(headers, CLIENT_METHOD_HEADER, "ListRelations");
setHeaderIfNotSet(headers, CLIENT_BULK_REQUEST_ID_HEADER, generateRandomIdWithNonUniqueFallback());
if (!relations?.length) {
throw new FgaValidationError("relations", "When calling listRelations, at least one relation must be passed in the relations field");
}
const batchCheckResults = await this.batchCheck(relations.map(relation => ({
user,
relation,
object,
contextualTuples,
context,
})), { ...options, headers, maxParallelRequests });
const firstErrorResponse = batchCheckResults.responses.find(response => (response as any).error);
if (firstErrorResponse) {
throw (firstErrorResponse as any).error;
}
return { relations: batchCheckResults.responses.filter(result => result.allowed).map(result => result._request.relation) };
}
/**
* ListUsers - List the objects of a particular type that the user has a certain relation to (evaluates)
* @param {ClientListUsersRequest} body
* @param {ClientRequestOptsWithConsistency} [options]
* @param {string} [options.authorizationModelId] - Overrides the authorization model id in the configuration
* @param {object} [options.headers] - Custom headers to send alongside the request
* @param {ConsistencyPreference} [options.consistency] - The consistency preference to use
* @param {object} [options.retryParams] - Override the retry parameters for this request
* @param {number} [options.retryParams.maxRetry] - Override the max number of retries on each API request
* @param {number} [options.retryParams.minWaitInMs] - Override the minimum wait before a retry is initiated
*/
async listUsers(body: ClientListUsersRequest, options: ClientRequestOptsWithConsistency = {}): PromiseResult<ListUsersResponse> {
return this.api.listUsers(this.getStoreId(options)!, {
authorization_model_id: this.getAuthorizationModelId(options),
relation: body.relation,
object: body.object,
user_filters: body.user_filters,
context: body.context,
contextual_tuples: body.contextualTuples || [],
consistency: options.consistency
}, options);
}
/**************
* Assertions *
**************/
/**
* ReadAssertions - Read assertions for a particular authorization model
* @param {ClientRequestOptsWithAuthZModelId} [options]
* @param {string} [options.authorizationModelId] - Overrides the authorization model id in the configuration
* @param {object} [options.headers] - Custom headers to send alongside the request
* @param {object} [options.retryParams] - Override the retry parameters for this request
* @param {number} [options.retryParams.maxRetry] - Override the max number of retries on each API request
* @param {number} [options.retryParams.minWaitInMs] - Override the minimum wait before a retry is initiated
*/
async readAssertions(options: ClientRequestOptsWithAuthZModelId = {}): PromiseResult<ReadAssertionsResponse> {
return this.api.readAssertions(this.getStoreId(options)!, this.getAuthorizationModelId(options)!, options);
}
/**
* WriteAssertions - Updates assertions for a particular authorization model
* @param {ClientWriteAssertionsRequest} assertions
* @param {ClientRequestOptsWithAuthZModelId} [options]
* @param {string} [options.authorizationModelId] - Overrides the authorization model id in the configuration
* @param {object} [options.headers] - Custom headers to send alongside the request
* @param {object} [options.retryParams] - Override the retry parameters for this request
* @param {number} [options.retryParams.maxRetry] - Override the max number of retries on each API request
* @param {number} [options.retryParams.minWaitInMs] - Override the minimum wait before a retry is initiated
*/
async writeAssertions(assertions: ClientWriteAssertionsRequest, options: ClientRequestOptsWithAuthZModelId = {}): PromiseResult<void> {
return this.api.writeAssertions(this.getStoreId(options)!, this.getAuthorizationModelId(options)!, {
assertions: assertions.map(assertion => ({
tuple_key: {
user: assertion.user,
relation: assertion.relation,
object: assertion.object,
},
expectation: assertion.expectation,
}))
}, options);
}
}