-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathdavinci.api.ts
More file actions
425 lines (376 loc) · 14.3 KB
/
davinci.api.ts
File metadata and controls
425 lines (376 loc) · 14.3 KB
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
/*
* Copyright (c) 2025 Ping Identity Corporation. All rights reserved.
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
/**
* Import the RTK Query library from Redux Toolkit
* @see https://redux-toolkit.js.org/rtk-query/overview
*/
import {
createApi,
FetchArgs,
fetchBaseQuery,
FetchBaseQueryError,
FetchBaseQueryMeta,
QueryReturnValue,
} from '@reduxjs/toolkit/query';
/**
* Import internal modules
*/
import { initQuery } from '@forgerock/sdk-request-middleware';
import type { logger as loggerFn } from '@forgerock/sdk-logger';
import { createAuthorizeUrl } from '@forgerock/sdk-oidc';
import type { RequestMiddleware } from '@forgerock/sdk-request-middleware';
import { handleResponse, transformActionRequest, transformSubmitRequest } from './davinci.utils.js';
/**
* Import the DaVinci types
*/
import type { RootStateWithNode } from './client.store.utils.js';
import type {
DaVinciCacheEntry,
OutgoingQueryParams,
StartOptions,
ThrownQueryError,
} from './davinci.types.js';
import type { ContinueNode } from './node.types.js';
import type { StartNode } from '../types.js';
import { ActionTypes } from '@forgerock/sdk-request-middleware';
type BaseQueryResponse = Promise<
QueryReturnValue<unknown, FetchBaseQueryError, FetchBaseQueryMeta>
>;
interface Extras<ActionType extends ActionTypes = ActionTypes, Payload = unknown> {
requestMiddleware: RequestMiddleware<ActionType, Payload>[];
logger: ReturnType<typeof loggerFn>;
}
/**
* @const davinciApi - Define the DaVinci API for Redux state management
* @see https://redux-toolkit.js.org/rtk-query/overview
*/
export const davinciApi = createApi({
reducerPath: 'davinci',
// TODO: implement extraOptions for request interceptors: https://stackoverflow.com/a/77569083 & https://stackoverflow.com/a/65129117
baseQuery: fetchBaseQuery({
prepareHeaders: (headers) => {
headers.set('Accept', 'application/json');
headers.set('x-requested-with', 'ping-sdk');
headers.set('x-requested-platform', 'javascript');
return headers;
},
}),
endpoints: (builder) => ({
/**
* @method flow - method for initiating a new flow with the DaVinci API
*/
flow: builder.mutation({
/**
* @method queryFn - This is just a wrapper around the fetch call
*/
async queryFn(params, api, __, baseQuery) {
const state = api.getState() as RootStateWithNode<ContinueNode>;
const links = state.node.server._links;
const requestBody = transformActionRequest(
state.node,
params.action,
(api.extra as Extras).logger,
);
const { requestMiddleware, logger } = api.extra as Extras;
let href = '';
if (links && 'next' in links) {
href = links['next'].href || '';
}
const request: FetchArgs = {
// TODO: If we don't have a `next.href`, we should handle this better
url: href,
credentials: 'include',
method: 'POST',
headers: {
'Content-Type': 'application/json',
interactionId: state.node.server.interactionId,
interactionToken: state.node.server.interactionToken,
},
body: JSON.stringify(requestBody),
};
logger.debug('Davinci API request', request);
const response: BaseQueryResponse = initQuery(request, 'flow')
.applyMiddleware(requestMiddleware)
.applyQuery(async (req: FetchArgs) => await baseQuery(req));
/**
* Returns the original response from DaVinci,
* this gets transformed in the onQueryStarted method
*/
return response;
},
/**
* @method onQueryStarted - method for handling the response from the DaVinci API
*
* The method name below is a bit misleading. It is not just
* called when the query is started, but throughout the lifecycle of
* the API, including when the query is fulfilled. This is because
* the query is started, and then the response is awaited, and then
* the response is processed.
*
* NOTE: The below is repeated for each endpoint, which is not "DRY",
* but doing it inline reduces the typing complexity as all the
* parameters are pre-typed from the library.
*/
async onQueryStarted(_, api) {
const logger = (api.extra as Extras).logger;
let response;
try {
const query = await api.queryFulfilled;
response = query.meta?.response;
} catch (err: unknown) {
const error = err as ThrownQueryError;
/**
* This error is thrown when the query is rejected. We don't
* want to do anything with it for now.
*/
response = error.meta?.response;
}
const cacheEntry: DaVinciCacheEntry = api.getCacheEntry();
logger.debug('Davinci API response', cacheEntry);
handleResponse(cacheEntry, api.dispatch, response?.status || 0, logger);
},
}),
/**
* @method next - method for initiating the next node in the current flow
*/
next: builder.mutation({
/**
* @method queryFn - This is just a wrapper around the fetch call
*/
async queryFn(body, api, __, baseQuery) {
const state = api.getState() as RootStateWithNode<ContinueNode>;
const links = state.node.server._links;
const { requestMiddleware, logger } = api.extra as Extras;
let requestBody;
let href = '';
if (links && 'next' in links) {
href = links['next'].href || '';
}
if (!body) {
requestBody = transformSubmitRequest(state.node, logger);
} else {
requestBody = body;
}
const request: FetchArgs = {
url: href,
credentials: 'include',
method: 'POST',
headers: {
'Content-Type': 'application/json',
interactionId: state.node.server.interactionId,
interactionToken: state.node.server.interactionToken,
},
body: JSON.stringify(requestBody),
};
logger.debug('Davinci API request', request);
const response: BaseQueryResponse = initQuery(request, 'next')
.applyMiddleware(requestMiddleware)
.applyQuery(async (req: FetchArgs) => await baseQuery(req));
/**
* Returns the original response from DaVinci,
* this gets transformed in the onQueryStarted method
*/
return response;
},
/**
* @method onQueryStarted - method for handling the response from the DaVinci API
*
* The method name below is a bit misleading. It is not just
* called when the query is started, but throughout the lifecycle of
* the API, including when the query is fulfilled. This is because
* the query is started, and then the response is awaited, and then
* the response is processed.
*
* NOTE: The below is repeated for each endpoint, which is not "DRY",
* but doing it inline reduces the typing complexity as all the
* parameters are pre-typed from the library.
*/
async onQueryStarted(_, api) {
const logger = (api.extra as Extras).logger;
let response;
try {
const query = await api.queryFulfilled;
response = query.meta?.response;
} catch (err: unknown) {
const error = err as ThrownQueryError;
/**
* This error is thrown when the query is rejected. We don't
* want to do anything with it for now.
*/
response = error.meta?.response;
}
const cacheEntry: DaVinciCacheEntry = api.getCacheEntry();
logger.debug('Davinci API response', cacheEntry);
handleResponse(cacheEntry, api.dispatch, response?.status || 0, logger);
},
}),
/**
* @method start - method for initiating a DaVinci flow
* @param - needs no arguments, but need to declare types to make it explicit
*/
start: builder.mutation<unknown, StartOptions<OutgoingQueryParams> | undefined>({
/**
* @method queryFn - This is just a wrapper around the fetch call
*/
async queryFn(options, api, __, baseQuery) {
const { requestMiddleware, logger } = api.extra as Extras;
const state = api.getState() as RootStateWithNode<StartNode>;
if (!state) {
return {
error: {
status: 400,
data: 'Store must be initialized before use',
},
};
}
const authorizeEndpoint = state.config.endpoints.authorize;
if (!authorizeEndpoint) {
return { error: { status: 400, data: 'authorizeEndpoint URL must be set' } };
}
try {
const authorizeUrl = await createAuthorizeUrl(authorizeEndpoint, {
clientId: state?.config?.clientId,
login: 'redirect', // TODO: improve this in SDK to be more semantic
redirectUri: state?.config?.redirectUri,
responseType: state?.config?.responseType as 'code',
scope: state?.config?.scope,
});
const url = new URL(authorizeUrl);
const existingParams = url.searchParams;
if (options?.query) {
Object.entries(options.query).forEach(([key, value]) => {
/**
* We use set here because if we have existing params, we want
* to make sure we override them and not add duplicates
*/
existingParams.set(key, String(value));
});
url.search = existingParams.toString();
}
const request: FetchArgs = {
url: url.toString(),
credentials: 'include',
method: 'GET',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
};
logger.debug('Davinci API request', request);
const response: BaseQueryResponse = initQuery(request, 'start')
.applyMiddleware(requestMiddleware)
.applyQuery(async (req: FetchArgs) => await baseQuery(req));
/**
* Returns the original response from DaVinci,
* this gets transformed in the onQueryStarted method
*/
return response;
} catch (error: unknown) {
if (error instanceof Error) {
return { error: { status: 400, data: error.message } };
}
return { error: { status: 400, data: 'An unknown error occurred' } };
}
},
/**
* @method onQueryStarted - method for handling the response from the DaVinci API
*
* The method name below is a bit misleading. It is not just
* called when the query is started, but throughout the lifecycle of
* the API, including when the query is fulfilled. This is because
* the query is started, and then the response is awaited, and then
* the response is processed.
*
* NOTE: The below is repeated for each endpoint, which is not "DRY",
* but doing it inline reduces the typing complexity as all the
* parameters are pre-typed from the library.
*/
async onQueryStarted(_, api) {
const logger = (api.extra as Extras).logger;
let response;
try {
const query = await api.queryFulfilled;
response = query.meta?.response;
} catch (err: unknown) {
const error = err as ThrownQueryError;
/**
* This error is thrown when the query is rejected. We don't
* want to do anything with it for now.
*/
response = error.meta?.response;
}
const cacheEntry: DaVinciCacheEntry = api.getCacheEntry();
logger.debug('Davinci API response', cacheEntry);
handleResponse(cacheEntry, api.dispatch, response?.status || 0, logger);
},
}),
resume: builder.query<unknown, { serverInfo: ContinueNode['server']; continueToken: string }>({
async queryFn({ serverInfo, continueToken }, api, _c, baseQuery) {
const { requestMiddleware, logger } = api.extra as Extras;
const links = serverInfo._links;
if (!continueToken) {
return {
error: {
data: 'No continue token',
message:
'Resume meant to be called in a social login. Continue token was not found on the url',
status: 200,
},
};
}
if (
!links ||
!('continue' in links) ||
!('href' in links['continue']) ||
!links['continue'].href
) {
return {
error: {
data: 'No continue url',
message:
'Resume needs a continue url, none was found in storage. Please restart your flow',
status: 200,
},
};
}
const continueUrl = links['continue'].href;
const request: FetchArgs = {
url: continueUrl,
credentials: 'include',
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${continueToken}`,
},
body: JSON.stringify({}),
};
logger.debug('Davinci API request', request);
const response: BaseQueryResponse = initQuery(request, 'resume')
.applyMiddleware(requestMiddleware)
.applyQuery(async (req: FetchArgs) => await baseQuery(req));
return response;
},
async onQueryStarted(_, api) {
const logger = (api.extra as Extras).logger;
let response;
try {
const query = await api.queryFulfilled;
response = query.meta?.response;
} catch (err: unknown) {
const error = err as ThrownQueryError;
/**
* This error is thrown when the query is rejected. We don't
* want to do anything with it for now.
*/
response = error.meta?.response;
}
const cacheEntry: DaVinciCacheEntry = api.getCacheEntry();
logger.debug('Davinci API response', cacheEntry);
handleResponse(cacheEntry, api.dispatch, response?.status || 0, logger);
},
}),
}),
});