-
Notifications
You must be signed in to change notification settings - Fork 212
/
Copy pathresolver_builder.js
910 lines (910 loc) · 40.2 KB
/
resolver_builder.js
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
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
"use strict";
// Copyright IBM Corp. 2018. All Rights Reserved.
// Node module: openapi-to-graphql
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
Object.defineProperty(exports, "__esModule", { value: true });
exports.extractRequestDataFromArgs = exports.getResolver = exports.getPublishResolver = exports.getSubscribe = exports.OPENAPI_TO_GRAPHQL = void 0;
const NodeRequest = require("request");
// Imports:
const Oas3Tools = require("./oas_3_tools");
const querystring = require("querystring");
const JSONPath = require("jsonpath-plus");
const debug_1 = require("debug");
const graphql_1 = require("graphql");
const form_urlencoded_1 = require("form-urlencoded");
const graphql_subscriptions_1 = require("graphql-subscriptions");
const merge = require("merge-deep");
const pubsub = new graphql_subscriptions_1.PubSub();
const translationLog = debug_1.debug('translation');
const httpLog = debug_1.debug('http');
const pubsubLog = debug_1.debug('pubsub');
// OAS runtime expression reference locations
const RUNTIME_REFERENCES = ['header.', 'query.', 'path.', 'body'];
exports.OPENAPI_TO_GRAPHQL = '_openAPIToGraphQL';
/*
* If the operation type is Subscription, create and return a resolver object
* that contains subscribe to perform subscription and resolve to execute
* payload transformation
*/
function getSubscribe({ operation, payloadName, data, baseUrl, connectOptions }) {
// Determine the appropriate URL:
if (typeof baseUrl === 'undefined') {
baseUrl = Oas3Tools.getBaseUrl(operation);
}
// Return custom resolver if it is defined
const customResolvers = data.options.customSubscriptionResolvers;
const title = operation.oas.info.title;
const path = operation.path;
const method = operation.method;
if (typeof customResolvers === 'object' &&
typeof customResolvers[title] === 'object' &&
typeof customResolvers[title][path] === 'object' &&
typeof customResolvers[title][path][method] === 'object' &&
typeof customResolvers[title][path][method].subscribe === 'function') {
translationLog(`Use custom publish resolver for ${operation.operationString}`);
return customResolvers[title][path][method].subscribe;
}
return (root, args, context, info) => {
/**
* Determine possible topic(s) by resolving callback path
*
* GraphQL produces sanitized payload names, so we have to sanitize before
* lookup here
*/
const paramName = Oas3Tools.sanitize(payloadName, Oas3Tools.CaseStyle.camelCase);
let resolveData = {};
if (payloadName && typeof payloadName === 'string') {
// The option genericPayloadArgName will change the payload name to "requestBody"
const sanePayloadName = data.options.genericPayloadArgName
? 'requestBody'
: Oas3Tools.sanitize(payloadName, Oas3Tools.CaseStyle.camelCase);
if (sanePayloadName in args) {
if (typeof args[sanePayloadName] === 'object') {
const rawPayload = Oas3Tools.desanitizeObjectKeys(args[sanePayloadName], data.saneMap);
resolveData.usedPayload = rawPayload;
}
else {
const rawPayload = JSON.parse(args[sanePayloadName]);
resolveData.usedPayload = rawPayload;
}
}
}
if (connectOptions) {
resolveData.usedRequestOptions = connectOptions;
}
else {
resolveData.usedRequestOptions = {
method: resolveData.usedPayload.method
? resolveData.usedPayload.method
: method.toUpperCase()
};
}
pubsubLog(`Subscription schema: ${JSON.stringify(resolveData.usedPayload)}`);
let value = path;
let paramNameWithoutLocation = paramName;
if (paramName.indexOf('.') !== -1) {
paramNameWithoutLocation = paramName.split('.')[1];
}
// See if the callback path contains constants expression
if (value.search(/{|}/) === -1) {
args[paramNameWithoutLocation] = isRuntimeExpression(value)
? resolveRuntimeExpression(paramName, value, resolveData, root, args)
: value;
}
else {
// Replace callback expression with appropriate values
const cbParams = value.match(/{([^}]*)}/g);
pubsubLog(`Analyzing subscription path: ${cbParams.toString()}`);
cbParams.forEach((cbParam) => {
value = value.replace(cbParam, resolveRuntimeExpression(paramName, cbParam.substring(1, cbParam.length - 1), resolveData, root, args));
});
args[paramNameWithoutLocation] = value;
}
const topic = args[paramNameWithoutLocation] || 'test';
pubsubLog(`Subscribing to: ${topic}`);
return context.pubsub
? context.pubsub.asyncIterator(topic)
: pubsub.asyncIterator(topic);
};
}
exports.getSubscribe = getSubscribe;
/*
* If the operation type is Subscription, create and return a resolver function
* triggered after a message has been published to the corresponding subscribe
* topic(s) to execute payload transformation
*/
function getPublishResolver({ operation, responseName, data }) {
// Return custom resolver if it is defined
const customResolvers = data.options.customSubscriptionResolvers;
const title = operation.oas.info.title;
const path = operation.path;
const method = operation.method;
if (typeof customResolvers === 'object' &&
typeof customResolvers[title] === 'object' &&
typeof customResolvers[title][path] === 'object' &&
typeof customResolvers[title][path][method] === 'object' &&
typeof customResolvers[title][path][method].resolve === 'function') {
translationLog(`Use custom publish resolver for ${operation.operationString}`);
return customResolvers[title][path][method].resolve;
}
return (payload, args, context, info) => {
// Validate and format based on operation.responseDefinition
const typeOfResponse = operation.responseDefinition.targetGraphQLType;
pubsubLog(`Message received: ${responseName}, ${typeOfResponse}, ${JSON.stringify(payload)}`);
let responseBody;
let saneData;
if (typeof payload === 'object') {
if (typeOfResponse === 'object') {
if (Buffer.isBuffer(payload)) {
try {
responseBody = JSON.parse(payload.toString());
}
catch (e) {
const errorString = `Cannot JSON parse payload` +
`operation ${operation.operationString} ` +
`even though it has content-type 'application/json'`;
pubsubLog(errorString);
return null;
}
}
else {
responseBody = payload;
}
saneData = Oas3Tools.sanitizeObjectKeys(payload);
}
else if ((Buffer.isBuffer(payload) || Array.isArray(payload)) &&
typeOfResponse === 'string') {
saneData = payload.toString();
}
}
else if (typeof payload === 'string') {
if (typeOfResponse === 'object') {
try {
responseBody = JSON.parse(payload);
saneData = Oas3Tools.sanitizeObjectKeys(responseBody);
}
catch (e) {
const errorString = `Cannot JSON parse payload` +
`operation ${operation.operationString} ` +
`even though it has content-type 'application/json'`;
pubsubLog(errorString);
return null;
}
}
else if (typeOfResponse === 'string') {
saneData = payload;
}
}
pubsubLog(`Message forwarded: ${JSON.stringify(saneData ? saneData : payload)}`);
return saneData ? saneData : payload;
};
}
exports.getPublishResolver = getPublishResolver;
/**
* If the operation type is Query or Mutation, create and return a resolver
* function that performs API requests for the given GraphQL query
*/
function getResolver({ operation, argsFromLink = {}, payloadName, data, baseUrl, requestOptions }) {
// Determine the appropriate URL:
if (typeof baseUrl === 'undefined') {
baseUrl = Oas3Tools.getBaseUrl(operation);
}
// Return custom resolver if it is defined
const customResolvers = data.options.customResolvers;
const title = operation.oas.info.title;
const path = operation.path;
const method = operation.method;
if (typeof customResolvers === 'object' &&
typeof customResolvers[title] === 'object' &&
typeof customResolvers[title][path] === 'object' &&
typeof customResolvers[title][path][method] === 'function') {
translationLog(`Use custom resolver for ${operation.operationString}`);
return customResolvers[title][path][method];
}
// Return resolve function:
return (source, args, context, info) => {
/**
* Fetch resolveData from possibly existing _openAPIToGraphQL
*
* NOTE: _openAPIToGraphQL is an object used to pass security info and data
* from previous resolvers
*/
let resolveData = {};
if (source &&
typeof source === 'object' &&
typeof source[exports.OPENAPI_TO_GRAPHQL] === 'object' &&
typeof source[exports.OPENAPI_TO_GRAPHQL].data === 'object') {
const parentIdentifier = getParentIdentifier(info);
if (!(parentIdentifier.length === 0) &&
parentIdentifier in source[exports.OPENAPI_TO_GRAPHQL].data) {
/**
* Resolving link params may change the usedParams, but these changes
* should not be present in the parent _openAPIToGraphQL, therefore copy
* the object
*/
resolveData = JSON.parse(JSON.stringify(source[exports.OPENAPI_TO_GRAPHQL].data[parentIdentifier]));
}
}
if (typeof resolveData.usedParams === 'undefined') {
resolveData.usedParams = {};
}
/**
* Handle default values of parameters, if they have not yet been defined by
* the user.
*/
operation.parameters.forEach((param) => {
const saneParamName = Oas3Tools.sanitize(param.name, !data.options.simpleNames
? Oas3Tools.CaseStyle.camelCase
: Oas3Tools.CaseStyle.simple);
if (typeof args[saneParamName] === 'undefined' &&
param.schema &&
typeof param.schema === 'object') {
let schema = param.schema;
if (schema && schema.$ref && typeof schema.$ref === 'string') {
schema = Oas3Tools.resolveRef(schema.$ref, operation.oas);
}
if (schema &&
schema.default &&
typeof schema.default !== 'undefined') {
args[saneParamName] = schema.default;
}
}
});
// Handle arguments provided by links
for (const paramName in argsFromLink) {
const saneParamName = Oas3Tools.sanitize(paramName, !data.options.simpleNames
? Oas3Tools.CaseStyle.camelCase
: Oas3Tools.CaseStyle.simple);
let value = argsFromLink[paramName];
/**
* see if the link parameter contains constants that are appended to the link parameter
*
* e.g. instead of:
* $response.body#/employerId
*
* it could be:
* abc_{$response.body#/employerId}
*/
if (value.search(/{|}/) === -1) {
args[saneParamName] = isRuntimeExpression(value)
? resolveRuntimeExpression(paramName, value, resolveData, source, args)
: value;
}
else {
// Replace link parameters with appropriate values
const linkParams = value.match(/{([^}]*)}/g);
linkParams.forEach((linkParam) => {
value = value.replace(linkParam, resolveRuntimeExpression(paramName, linkParam.substring(1, linkParam.length - 1), resolveData, source, args));
});
args[saneParamName] = value;
}
}
// Stored used parameters to future requests:
resolveData.usedParams = Object.assign(resolveData.usedParams, args);
// Build URL (i.e., fill in path parameters):
const { path, qs, headers } = extractRequestDataFromArgs(operation.path, operation.parameters, args, data);
const url = baseUrl + path;
/**
* The Content-Type and Accept property should not be changed because the
* object type has already been created and unlike these properties, it
* cannot be easily changed
*
* NOTE: This may cause the user to encounter unexpected changes
*/
if (operation.method !== Oas3Tools.HTTP_METHODS.get) {
headers['content-type'] =
typeof operation.payloadContentType !== 'undefined'
? operation.payloadContentType
: 'application/json';
}
headers['accept'] =
typeof operation.responseContentType !== 'undefined'
? operation.responseContentType
: 'application/json';
// Add `headers` option:
if (typeof data.options.headers === 'object') {
Object.assign(headers, data.options.headers);
}
else if (typeof data.options.headers === 'function') {
Object.assign(headers, data.options.headers(method, path, title, {
source,
args,
context,
info
}));
}
// Add `qs` option:
if (typeof data.options.qs === 'object') {
Object.assign(qs, data.options.qs);
}
// Get authentication headers and query string parameters
let cookieJar;
if (source &&
typeof source === 'object' &&
typeof source[exports.OPENAPI_TO_GRAPHQL] === 'object') {
const { authHeaders, authQs, authCookie } = getAuthOptions(operation, source[exports.OPENAPI_TO_GRAPHQL], data);
// ...and add them
Object.assign(headers, authHeaders);
Object.assign(qs, authQs);
// Add authentication cookie if created
if (authCookie !== null) {
cookieJar = NodeRequest.jar();
cookieJar.setCookie(authCookie, url);
}
}
// Extract OAuth token from context (if available)
if (data.options.sendOAuthTokenInQuery) {
const oAuthQueryObj = createOAuthQS(data, context);
Object.assign(qs, oAuthQueryObj);
}
else {
const oAuthHeader = createOAuthHeader(data, context);
Object.assign(headers, oAuthHeader);
}
/**
* Determine possible payload
*
* GraphQL produces sanitized payload names, so we have to sanitize before
* lookup here
*/
let payload;
if (typeof payloadName === 'string') {
// The option `genericPayloadArgName` will change the payload name to "requestBody"
const sanePayloadName = data.options.genericPayloadArgName
? 'requestBody'
: Oas3Tools.sanitize(payloadName, Oas3Tools.CaseStyle.camelCase);
if (operation.payloadContentType === 'application/json') {
payload = JSON.stringify(Oas3Tools.desanitizeObjectKeys(args[sanePayloadName], data.saneMap));
}
else if (operation.payloadContentType === 'application/x-www-form-urlencoded') {
payload = form_urlencoded_1.default(Oas3Tools.desanitizeObjectKeys(args[sanePayloadName], data.saneMap));
}
else {
// Payload is not an object
payload = args[sanePayloadName];
}
}
let options = {
method: operation.method,
url,
headers,
qs,
body: payload,
jar: cookieJar // For authentication cookies
};
// The options `requestOptions` will finalize the options
if (requestOptions) {
/**
* If requestOptions is a function, the run the function, otherwise,
* use the original value
*/
const requestOptionsValue = typeof requestOptions === 'function'
? requestOptions(method, path, title, { source, args, context, info }, options)
: requestOptions;
options = merge(options, requestOptionsValue);
}
resolveData.usedRequestOptions = options;
resolveData.usedPayload = payload;
resolveData.usedStatusCode = operation.statusCode;
// Make the call
httpLog(`Call ${options.method.toUpperCase()} ${options.url}?${querystring.stringify(options.qs)}\n` +
`headers: ${JSON.stringify(options.headers)}\n` +
`request body: ${options.body}`);
return new Promise((resolve, reject) => {
NodeRequest(options, (err, response, body) => {
if (err) {
httpLog(err);
reject(err);
}
else if (response.statusCode < 200 || response.statusCode > 299) {
httpLog(`${response.statusCode} - ${Oas3Tools.trim(body, 100)}`);
const errorString = `Could not invoke operation ${operation.operationString}`;
if (data.options.provideErrorExtensions) {
let responseBody;
try {
responseBody = JSON.parse(body);
}
catch (e) {
responseBody = body;
}
const extensions = {
method: operation.method,
path: operation.path,
statusCode: response.statusCode,
responseHeaders: response.headers,
responseBody
};
reject(graphQLErrorWithExtensions(errorString, extensions));
}
else {
reject(new Error(errorString));
}
// Successful response code 200-299
}
else {
httpLog(`${response.statusCode} - ${Oas3Tools.trim(body, 100)}`);
if (response.headers['content-type']) {
/**
* Throw warning if the non-application/json content does not
* match the OAS.
*
* Use an inclusion test in case of charset
*
* i.e. text/plain; charset=utf-8
*/
if (!(response.headers['content-type'].includes(operation.responseContentType) ||
operation.responseContentType.includes(response.headers['content-type']))) {
const errorString = `Operation ` +
`${operation.operationString} ` +
`should have a content-type '${operation.responseContentType}' ` +
`but has '${response.headers['content-type']}' instead`;
httpLog(errorString);
reject(errorString);
}
else {
/**
* If the response body is type JSON, then parse it
*
* content-type may not be necessarily 'application/json' it can be
* 'application/json; charset=utf-8' for example
*/
if (response.headers['content-type'].includes('application/json')) {
let responseBody;
try {
responseBody = JSON.parse(body);
}
catch (e) {
const errorString = `Cannot JSON parse response body of ` +
`operation ${operation.operationString} ` +
`even though it has content-type 'application/json'`;
httpLog(errorString);
reject(errorString);
}
resolveData.responseHeaders = response.headers;
// Deal with the fact that the server might send unsanitized data
let saneData = Oas3Tools.sanitizeObjectKeys(responseBody, !data.options.simpleNames
? Oas3Tools.CaseStyle.camelCase
: Oas3Tools.CaseStyle.simple);
// Pass on _openAPIToGraphQL to subsequent resolvers
if (saneData && typeof saneData === 'object') {
if (Array.isArray(saneData)) {
saneData.forEach((element) => {
if (typeof element[exports.OPENAPI_TO_GRAPHQL] === 'undefined') {
element[exports.OPENAPI_TO_GRAPHQL] = {
data: {}
};
}
if (source &&
typeof source === 'object' &&
typeof source[exports.OPENAPI_TO_GRAPHQL] === 'object') {
Object.assign(element[exports.OPENAPI_TO_GRAPHQL], source[exports.OPENAPI_TO_GRAPHQL]);
}
element[exports.OPENAPI_TO_GRAPHQL].data[getIdentifier(info)] = resolveData;
});
}
else {
if (typeof saneData[exports.OPENAPI_TO_GRAPHQL] === 'undefined') {
saneData[exports.OPENAPI_TO_GRAPHQL] = {
data: {}
};
}
if (source &&
typeof source === 'object' &&
typeof source[exports.OPENAPI_TO_GRAPHQL] === 'object') {
Object.assign(saneData[exports.OPENAPI_TO_GRAPHQL], source[exports.OPENAPI_TO_GRAPHQL]);
}
saneData[exports.OPENAPI_TO_GRAPHQL].data[getIdentifier(info)] = resolveData;
}
}
// Apply limit argument
if (data.options.addLimitArgument &&
/**
* NOTE: Does not differentiate between autogenerated args and
* preexisting args
*
* Ensure that there is not preexisting 'limit' argument
*/
!operation.parameters.find((parameter) => {
return parameter.name === 'limit';
}) &&
// Only array data
Array.isArray(saneData) &&
// Only array of objects/arrays
saneData.some((data) => {
return typeof data === 'object';
})) {
let arraySaneData = saneData;
if ('limit' in args) {
const limit = args['limit'];
if (limit >= 0) {
arraySaneData = arraySaneData.slice(0, limit);
}
else {
reject(new Error(`Auto-generated 'limit' argument must be greater than or equal to 0`));
}
}
else {
reject(new Error(`Cannot get value for auto-generated 'limit' argument`));
}
saneData = arraySaneData;
}
resolve(saneData);
}
else {
// TODO: Handle YAML
resolve(body);
}
}
}
else {
/**
* Check to see if there is not supposed to be a response body,
* if that is the case, that would explain why there is not
* a content-type
*/
const { responseContentType } = Oas3Tools.getResponseObject(operation, operation.statusCode, operation.oas);
if (responseContentType === null) {
resolve(null);
}
else {
const errorString = 'Response does not have a Content-Type property';
httpLog(errorString);
reject(errorString);
}
}
}
});
});
};
}
exports.getResolver = getResolver;
/**
* Attempts to create an object to become an OAuth query string by extracting an
* OAuth token from the context based on the JSON path provided in the options.
*/
function createOAuthQS(data, context) {
return typeof data.options.tokenJSONpath !== 'string'
? {}
: extractToken(data, context);
}
function extractToken(data, context) {
const tokenJSONpath = data.options.tokenJSONpath;
const tokens = JSONPath.JSONPath({
path: tokenJSONpath,
json: context
});
if (Array.isArray(tokens) && tokens.length > 0) {
const token = tokens[0];
return {
access_token: token
};
}
else {
httpLog(`Warning: could not extract OAuth token from context at '${tokenJSONpath}'`);
return {};
}
}
/**
* Attempts to create an OAuth authorization header by extracting an OAuth token
* from the context based on the JSON path provided in the options.
*/
function createOAuthHeader(data, context) {
if (typeof data.options.tokenJSONpath !== 'string') {
return {};
}
// Extract token
const tokenJSONpath = data.options.tokenJSONpath;
const tokens = JSONPath.JSONPath({
path: tokenJSONpath,
json: context
});
if (Array.isArray(tokens) && tokens.length > 0) {
const token = tokens[0];
return {
Authorization: `Bearer ${token}`,
'User-Agent': 'openapi-to-graphql'
};
}
else {
httpLog(`Warning: could not extract OAuth token from context at ` +
`'${tokenJSONpath}'`);
return {};
}
}
/**
* Return the headers and query strings to authenticate a request (if any).
* Return authHeader and authQs, which hold headers and query parameters
* respectively to authentication a request.
*/
function getAuthOptions(operation, _openAPIToGraphQL, data) {
const authHeaders = {};
const authQs = {};
let authCookie = null;
/**
* Determine if authentication is required, and which protocol (if any) we can
* use
*/
const { authRequired, securityRequirement, sanitizedSecurityRequirement } = getAuthReqAndProtcolName(operation, _openAPIToGraphQL);
// Possibly, we don't need to do anything:
if (!authRequired) {
return { authHeaders, authQs, authCookie };
}
// If authentication is required, but we can't fulfill the protocol, throw:
if (authRequired && typeof securityRequirement !== 'string') {
throw new Error(`Missing information to authenticate API request.`);
}
if (typeof securityRequirement === 'string') {
const security = data.security[securityRequirement];
switch (security.def.type) {
case 'apiKey':
const apiKey = _openAPIToGraphQL.security[sanitizedSecurityRequirement].apiKey;
if ('in' in security.def) {
if (typeof security.def.name === 'string') {
if (security.def.in === 'header') {
authHeaders[security.def.name] = apiKey;
}
else if (security.def.in === 'query') {
authQs[security.def.name] = apiKey;
}
else if (security.def.in === 'cookie') {
authCookie = NodeRequest.cookie(`${security.def.name}=${apiKey}`);
}
}
else {
throw new Error(`Cannot send API key in '${JSON.stringify(security.def.in)}'`);
}
}
break;
case 'http':
switch (security.def.scheme) {
case 'basic':
const username = _openAPIToGraphQL.security[sanitizedSecurityRequirement].username;
const password = _openAPIToGraphQL.security[sanitizedSecurityRequirement].password;
const credentials = `${username}:${password}`;
authHeaders['Authorization'] = `Basic ${Buffer.from(credentials).toString('base64')}`;
break;
default:
throw new Error(`Cannot recognize http security scheme ` +
`'${JSON.stringify(security.def.scheme)}'`);
}
break;
case 'oauth2':
break;
case 'openIdConnect':
break;
default:
throw new Error(`Cannot recognize security type '${security.def.type}'`);
}
}
return { authHeaders, authQs, authCookie };
}
/**
* Determines whether a given operation requires authentication, and which of
* the (possibly multiple) authentication protocols can be used based on the
* data present in the given context.
*/
function getAuthReqAndProtcolName(operation, _openAPIToGraphQL) {
let authRequired = false;
if (Array.isArray(operation.securityRequirements) &&
operation.securityRequirements.length > 0) {
authRequired = true;
for (let securityRequirement of operation.securityRequirements) {
const sanitizedSecurityRequirement = Oas3Tools.sanitize(securityRequirement, Oas3Tools.CaseStyle.camelCase);
if (typeof _openAPIToGraphQL.security[sanitizedSecurityRequirement] ===
'object') {
return {
authRequired,
securityRequirement,
sanitizedSecurityRequirement
};
}
}
}
return {
authRequired
};
}
/**
* Given a link parameter or callback path, determine the value from the runtime
* expression
*
* The link parameter or callback path is a reference to data contained in the
* url/method/statuscode or response/request body/query/path/header
*/
function resolveRuntimeExpression(paramName, value, resolveData, root, args) {
if (value === '$url') {
return resolveData.usedRequestOptions.url;
}
else if (value === '$method') {
return resolveData.usedRequestOptions.method;
}
else if (value === '$statusCode') {
return resolveData.usedStatusCode;
}
else if (value.startsWith('$request.')) {
// CASE: parameter is previous body
if (value === '$request.body') {
return resolveData.usedPayload;
// CASE: parameter in previous body
}
else if (value.startsWith('$request.body#')) {
const tokens = JSONPath.JSONPath({
path: value.split('body#/')[1],
json: resolveData.usedPayload
});
if (Array.isArray(tokens) && tokens.length > 0) {
return tokens[0];
}
else {
httpLog(`Warning: could not extract parameter '${paramName}' from link`);
}
// CASE: parameter in previous query parameter
}
else if (value.startsWith('$request.query')) {
return resolveData.usedParams[Oas3Tools.sanitize(value.split('query.')[1], Oas3Tools.CaseStyle.camelCase)];
// CASE: parameter in previous path parameter
}
else if (value.startsWith('$request.path')) {
return resolveData.usedParams[Oas3Tools.sanitize(value.split('path.')[1], Oas3Tools.CaseStyle.camelCase)];
// CASE: parameter in previous header parameter
}
else if (value.startsWith('$request.header')) {
return resolveData.usedRequestOptions.headers[value.split('header.')[1]];
}
}
else if (value.startsWith('$response.')) {
/**
* CASE: parameter is body
*
* NOTE: may not be used because it implies that the operation does not
* return a JSON object and OpenAPI-to-GraphQL does not create GraphQL
* objects for non-JSON data and links can only exists between objects.
*/
if (value === '$response.body') {
const result = JSON.parse(JSON.stringify(root));
/**
* _openAPIToGraphQL contains data used by OpenAPI-to-GraphQL to create the GraphQL interface
* and should not be exposed
*/
result._openAPIToGraphQL = undefined;
return result;
// CASE: parameter in body
}
else if (value.startsWith('$response.body#')) {
const tokens = JSONPath.JSONPath({
path: value.split('body#/')[1],
json: root
});
if (Array.isArray(tokens) && tokens.length > 0) {
return tokens[0];
}
else {
httpLog(`Warning: could not extract parameter '${paramName}' from link`);
}
// CASE: parameter in query parameter
}
else if (value.startsWith('$response.query')) {
// NOTE: handled the same way $request.query is handled
return resolveData.usedParams[Oas3Tools.sanitize(value.split('query.')[1], Oas3Tools.CaseStyle.camelCase)];
// CASE: parameter in path parameter
}
else if (value.startsWith('$response.path')) {
// NOTE: handled the same way $request.path is handled
return resolveData.usedParams[Oas3Tools.sanitize(value.split('path.')[1], Oas3Tools.CaseStyle.camelCase)];
// CASE: parameter in header parameter
}
else if (value.startsWith('$response.header')) {
return resolveData.responseHeaders[value.split('header.')[1]];
}
}
throw new Error(`Cannot create link because '${value}' is an invalid runtime expression`);
}
/**
* Check if a string is a runtime expression in the context of link parameters
*/
function isRuntimeExpression(str) {
if (str === '$url' || str === '$method' || str === '$statusCode') {
return true;
}
else if (str.startsWith('$request.')) {
for (let i = 0; i < RUNTIME_REFERENCES.length; i++) {
if (str.startsWith(`$request.${RUNTIME_REFERENCES[i]}`)) {
return true;
}
}
}
else if (str.startsWith('$response.')) {
for (let i = 0; i < RUNTIME_REFERENCES.length; i++) {
if (str.startsWith(`$response.${RUNTIME_REFERENCES[i]}`)) {
return true;
}
}
}
return false;
}
/**
* From the info object provided by the resolver, get a unique identifier, which
* is the path formed from the nested field names (or aliases if provided)
*
* Used to store and retrieve the _openAPIToGraphQL of parent field
*/
function getIdentifier(info) {
return getIdentifierRecursive(info.path);
}
/**
* From the info object provided by the resolver, get the unique identifier of
* the parent object
*/
function getParentIdentifier(info) {
return getIdentifierRecursive(info.path.prev);
}
/**
* Get the path of nested field names (or aliases if provided)
*/
function getIdentifierRecursive(path) {
return typeof path.prev === 'undefined'
? path.key
: /**
* Check if the identifier contains array indexing, if so remove.
*
* i.e. instead of 0/friends/1/friends/2/friends/user, create
* friends/friends/friends/user
*/
isNaN(parseInt(path.key))
? `${path.key}/${getIdentifierRecursive(path.prev)}`
: getIdentifierRecursive(path.prev);
}
/**
* Create a new GraphQLError with an extensions field
*/
function graphQLErrorWithExtensions(message, extensions) {
return new graphql_1.GraphQLError(message, null, null, null, null, null, extensions);
}
/**
* Extracts data from the GraphQL arguments of a particular field
*
* Replaces the path parameter in the given path with values in the given args.
* Furthermore adds the query parameters for a request.
*/
function extractRequestDataFromArgs(path, parameters, args, // NOTE: argument keys are sanitized!
data) {
const qs = {};
const headers = {};
// Iterate parameters:
for (const param of parameters) {
const saneParamName = Oas3Tools.sanitize(param.name, !data.options.simpleNames
? Oas3Tools.CaseStyle.camelCase
: Oas3Tools.CaseStyle.simple);
if (saneParamName && saneParamName in args) {
switch (param.in) {
// Path parameters
case 'path':
path = path.replace(`{${param.name}}`, args[saneParamName]);
break;
// Query parameters
case 'query':
qs[param.name] = args[saneParamName];
break;
// Header parameters
case 'header':
headers[param.name] = args[saneParamName];
break;
// Cookie parameters
case 'cookie':
if (!('cookie' in headers)) {
headers['cookie'] = '';
}
headers['cookie'] += `${param.name}=${args[saneParamName]}; `;
break;
default:
httpLog(`Warning: The parameter location '${param.in}' in the ` +
`parameter '${param.name}' of operation '${path}' is not ` +
`supported`);
}
}
}
return { path, qs, headers };
}
exports.extractRequestDataFromArgs = extractRequestDataFromArgs;
//# sourceMappingURL=resolver_builder.js.map