@aws-amplify/api-graphql 4.0.1-api-v6-models.9351bcf.0 → 4.0.1-api-v6-models.891fe0d.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/internals/server/package.json +8 -0
  2. package/lib/GraphQLAPI.d.ts +1 -1
  3. package/lib/GraphQLAPI.js +23 -28
  4. package/lib/Providers/AWSAppSyncRealTimeProvider/index.js +467 -582
  5. package/lib/index.js +1 -1
  6. package/lib/internals/APIClient.d.ts +16 -1
  7. package/lib/internals/APIClient.js +232 -206
  8. package/lib/internals/InternalGraphQLAPI.d.ts +1 -1
  9. package/lib/internals/InternalGraphQLAPI.js +205 -247
  10. package/lib/internals/generateClient.js +14 -13
  11. package/lib/internals/generateModelsProperty.js +19 -312
  12. package/lib/internals/operations/get.d.ts +2 -0
  13. package/lib/internals/operations/get.js +59 -0
  14. package/lib/internals/operations/list.d.ts +2 -0
  15. package/lib/internals/operations/list.js +71 -0
  16. package/lib/internals/operations/observeQuery.d.ts +2 -0
  17. package/lib/internals/operations/observeQuery.js +119 -0
  18. package/lib/internals/operations/subscription.d.ts +1 -0
  19. package/lib/internals/operations/subscription.js +27 -0
  20. package/lib/internals/server/generateClient.d.ts +11 -0
  21. package/lib/internals/server/generateClient.js +30 -0
  22. package/lib/internals/server/generateModelsProperty.d.ts +3 -0
  23. package/lib/internals/server/generateModelsProperty.js +45 -0
  24. package/lib/internals/server/index.d.ts +1 -0
  25. package/lib/internals/server/index.js +7 -0
  26. package/lib/internals/v6.js +3 -3
  27. package/lib/tsconfig.tsbuildinfo +1 -1
  28. package/lib/types/index.d.ts +36 -4
  29. package/lib/utils/ConnectionStateMonitor.js +51 -64
  30. package/lib/utils/ReachabilityMonitor/index.js +2 -2
  31. package/lib/utils/ReachabilityMonitor/index.native.js +4 -6
  32. package/lib/utils/ReconnectionMonitor.js +20 -24
  33. package/lib/utils/errors/APIError.js +7 -11
  34. package/lib/utils/errors/assertValidationError.js +4 -4
  35. package/lib/utils/errors/validation.js +5 -6
  36. package/lib/utils/findIndexByFields.js +4 -9
  37. package/lib/utils/resolveConfig.js +9 -10
  38. package/lib/utils/resolveLibraryOptions.js +4 -5
  39. package/lib/utils/resolveOwnerFields.js +10 -33
  40. package/lib/utils/resolvePKFields.js +2 -3
  41. package/lib-esm/GraphQLAPI.d.ts +1 -1
  42. package/lib-esm/GraphQLAPI.js +23 -29
  43. package/lib-esm/Providers/AWSAppSyncRealTimeProvider/index.js +459 -575
  44. package/lib-esm/Providers/constants.js +10 -10
  45. package/lib-esm/internals/APIClient.d.ts +16 -1
  46. package/lib-esm/internals/APIClient.js +230 -205
  47. package/lib-esm/internals/InternalGraphQLAPI.d.ts +1 -1
  48. package/lib-esm/internals/InternalGraphQLAPI.js +201 -244
  49. package/lib-esm/internals/generateClient.js +11 -10
  50. package/lib-esm/internals/generateModelsProperty.js +19 -312
  51. package/lib-esm/internals/operations/get.d.ts +2 -0
  52. package/lib-esm/internals/operations/get.js +55 -0
  53. package/lib-esm/internals/operations/list.d.ts +2 -0
  54. package/lib-esm/internals/operations/list.js +67 -0
  55. package/lib-esm/internals/operations/observeQuery.d.ts +2 -0
  56. package/lib-esm/internals/operations/observeQuery.js +115 -0
  57. package/lib-esm/internals/operations/subscription.d.ts +1 -0
  58. package/lib-esm/internals/operations/subscription.js +23 -0
  59. package/lib-esm/internals/server/generateClient.d.ts +11 -0
  60. package/lib-esm/internals/server/generateClient.js +26 -0
  61. package/lib-esm/internals/server/generateModelsProperty.d.ts +3 -0
  62. package/lib-esm/internals/server/generateModelsProperty.js +41 -0
  63. package/lib-esm/internals/server/index.d.ts +1 -0
  64. package/lib-esm/internals/server/index.js +3 -0
  65. package/lib-esm/internals/v6.js +1 -1
  66. package/lib-esm/tsconfig.tsbuildinfo +1 -1
  67. package/lib-esm/types/index.d.ts +36 -4
  68. package/lib-esm/types/index.js +3 -3
  69. package/lib-esm/utils/ConnectionStateMonitor.js +49 -63
  70. package/lib-esm/utils/ReachabilityMonitor/index.js +1 -1
  71. package/lib-esm/utils/ReachabilityMonitor/index.native.js +1 -3
  72. package/lib-esm/utils/ReconnectionMonitor.js +19 -24
  73. package/lib-esm/utils/errors/APIError.js +6 -11
  74. package/lib-esm/utils/errors/assertValidationError.js +2 -2
  75. package/lib-esm/utils/errors/validation.js +5 -6
  76. package/lib-esm/utils/findIndexByFields.js +4 -9
  77. package/lib-esm/utils/resolveConfig.js +8 -9
  78. package/lib-esm/utils/resolveLibraryOptions.js +4 -5
  79. package/lib-esm/utils/resolveOwnerFields.js +10 -33
  80. package/lib-esm/utils/resolvePKFields.js +2 -3
  81. package/package.json +8 -7
  82. package/src/GraphQLAPI.ts +6 -2
  83. package/src/Providers/AWSAppSyncRealTimeProvider/index.ts +6 -5
  84. package/src/internals/APIClient.ts +122 -35
  85. package/src/internals/InternalGraphQLAPI.ts +35 -10
  86. package/src/internals/generateClient.ts +0 -1
  87. package/src/internals/generateModelsProperty.ts +27 -340
  88. package/src/internals/operations/get.ts +121 -0
  89. package/src/internals/operations/list.ts +111 -0
  90. package/src/internals/operations/observeQuery.ts +140 -0
  91. package/src/internals/operations/subscription.ts +59 -0
  92. package/src/internals/server/generateClient.ts +45 -0
  93. package/src/internals/server/generateModelsProperty.ts +70 -0
  94. package/src/internals/server/index.ts +4 -0
  95. package/src/types/index.ts +65 -9
@@ -37,7 +37,7 @@ export declare class InternalGraphQLAPIClass {
37
37
  * @param [additionalHeaders] - headers to merge in after any `graphql_headers` set in the config
38
38
  * @returns An Observable if the query is a subscription query, else a promise of the graphql result.
39
39
  */
40
- graphql<T = any>(amplify: AmplifyClassV6, { query: paramQuery, variables, authMode, authToken }: GraphQLOptions, additionalHeaders?: {
40
+ graphql<T = any>(amplify: AmplifyClassV6 | ((fn: (amplify: any) => Promise<any>) => Promise<AmplifyClassV6>), { query: paramQuery, variables, authMode, authToken }: GraphQLOptions, additionalHeaders?: {
41
41
  [key: string]: string;
42
42
  }, customUserAgentDetails?: CustomUserAgentDetails): Observable<GraphQLResult<T>> | Promise<GraphQLResult<T>>;
43
43
  private _graphql;
@@ -1,37 +1,36 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.InternalGraphQLAPI = exports.InternalGraphQLAPIClass = exports.graphqlOperation = void 0;
4
- var tslib_1 = require("tslib");
5
4
  // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
6
5
  // SPDX-License-Identifier: Apache-2.0
7
- var graphql_1 = require("graphql");
8
- var core_1 = require("@aws-amplify/core");
9
- var utils_1 = require("@aws-amplify/core/internals/utils");
10
- var types_1 = require("../types");
11
- var api_rest_1 = require("@aws-amplify/api-rest");
12
- var internals_1 = require("@aws-amplify/api-rest/internals");
13
- var AWSAppSyncRealTimeProvider_1 = require("../Providers/AWSAppSyncRealTimeProvider");
14
- var utils_2 = require("../utils");
15
- var USER_AGENT_HEADER = 'x-amz-user-agent';
16
- var logger = new core_1.ConsoleLogger('GraphQLAPI');
17
- var graphqlOperation = function (query, variables, authToken) {
18
- if (variables === void 0) { variables = {}; }
19
- return ({
20
- query: query,
21
- variables: variables,
22
- authToken: authToken,
23
- });
24
- };
6
+ const graphql_1 = require("graphql");
7
+ const core_1 = require("@aws-amplify/core");
8
+ const utils_1 = require("@aws-amplify/core/internals/utils");
9
+ const types_1 = require("../types");
10
+ const api_rest_1 = require("@aws-amplify/api-rest");
11
+ const internals_1 = require("@aws-amplify/api-rest/internals");
12
+ const AWSAppSyncRealTimeProvider_1 = require("../Providers/AWSAppSyncRealTimeProvider");
13
+ const utils_2 = require("../utils");
14
+ const USER_AGENT_HEADER = 'x-amz-user-agent';
15
+ const logger = new core_1.ConsoleLogger('GraphQLAPI');
16
+ const graphqlOperation = (query, variables = {}, authToken) => ({
17
+ query,
18
+ variables,
19
+ authToken,
20
+ });
25
21
  exports.graphqlOperation = graphqlOperation;
22
+ const isAmplifyInstance = (amplify) => {
23
+ return typeof amplify !== 'function';
24
+ };
26
25
  /**
27
26
  * Export Cloud Logic APIs
28
27
  */
29
- var InternalGraphQLAPIClass = /** @class */ (function () {
28
+ class InternalGraphQLAPIClass {
30
29
  /**
31
30
  * Initialize GraphQL API with AWS configuration
32
31
  * @param {Object} options - Configuration object for API
33
32
  */
34
- function InternalGraphQLAPIClass(options) {
33
+ constructor(options) {
35
34
  this._api = {
36
35
  post: internals_1.post,
37
36
  cancelREST: internals_1.cancel,
@@ -41,88 +40,70 @@ var InternalGraphQLAPIClass = /** @class */ (function () {
41
40
  this._options = options;
42
41
  logger.debug('API Options', this._options);
43
42
  }
44
- InternalGraphQLAPIClass.prototype.getModuleName = function () {
43
+ getModuleName() {
45
44
  return 'InternalGraphQLAPI';
46
- };
47
- InternalGraphQLAPIClass.prototype._headerBasedAuth = function (amplify, authMode, additionalHeaders) {
48
- var _a;
49
- if (additionalHeaders === void 0) { additionalHeaders = {}; }
50
- return tslib_1.__awaiter(this, void 0, void 0, function () {
51
- var config, _b, region, appSyncGraphqlEndpoint, apiKey, defaultAuthMode, authenticationType, headers, _c, session, token, e_1;
52
- return tslib_1.__generator(this, function (_d) {
53
- switch (_d.label) {
54
- case 0:
55
- config = amplify.getConfig();
56
- _b = (0, utils_2.resolveConfig)(amplify), region = _b.region, appSyncGraphqlEndpoint = _b.endpoint, apiKey = _b.apiKey, defaultAuthMode = _b.defaultAuthMode;
57
- authenticationType = authMode || defaultAuthMode || 'iam';
58
- headers = {};
59
- _c = authenticationType;
60
- switch (_c) {
61
- case 'apiKey': return [3 /*break*/, 1];
62
- case 'iam': return [3 /*break*/, 2];
63
- case 'oidc': return [3 /*break*/, 4];
64
- case 'userPool': return [3 /*break*/, 4];
65
- case 'lambda': return [3 /*break*/, 8];
66
- case 'none': return [3 /*break*/, 9];
67
- }
68
- return [3 /*break*/, 10];
69
- case 1:
70
- if (!apiKey) {
71
- throw new Error(types_1.GraphQLAuthError.NO_API_KEY);
72
- }
73
- headers = {
74
- 'X-Api-Key': apiKey,
75
- };
76
- return [3 /*break*/, 11];
77
- case 2: return [4 /*yield*/, amplify.Auth.fetchAuthSession()];
78
- case 3:
79
- session = _d.sent();
80
- if (session.credentials === undefined) {
81
- throw new Error(types_1.GraphQLAuthError.NO_CREDENTIALS);
82
- }
83
- return [3 /*break*/, 11];
84
- case 4:
85
- _d.trys.push([4, 6, , 7]);
86
- token = void 0;
87
- return [4 /*yield*/, amplify.Auth.fetchAuthSession()];
88
- case 5:
89
- token = (_a = (_d.sent()).tokens) === null || _a === void 0 ? void 0 : _a.accessToken.toString();
90
- if (!token) {
91
- throw new Error(types_1.GraphQLAuthError.NO_FEDERATED_JWT);
92
- }
93
- headers = {
94
- Authorization: token,
95
- };
96
- return [3 /*break*/, 7];
97
- case 6:
98
- e_1 = _d.sent();
99
- throw new Error(types_1.GraphQLAuthError.NO_CURRENT_USER);
100
- case 7: return [3 /*break*/, 11];
101
- case 8:
102
- if (!additionalHeaders.Authorization) {
103
- throw new Error(types_1.GraphQLAuthError.NO_AUTH_TOKEN);
104
- }
105
- headers = {
106
- Authorization: additionalHeaders.Authorization,
107
- };
108
- return [3 /*break*/, 11];
109
- case 9: return [3 /*break*/, 11];
110
- case 10: return [3 /*break*/, 11];
111
- case 11: return [2 /*return*/, headers];
45
+ }
46
+ async _headerBasedAuth(amplify, authMode, additionalHeaders = {}) {
47
+ const config = amplify.getConfig();
48
+ const { region: region, endpoint: appSyncGraphqlEndpoint, apiKey, defaultAuthMode, } = (0, utils_2.resolveConfig)(amplify);
49
+ const authenticationType = authMode || defaultAuthMode || 'iam';
50
+ let headers = {};
51
+ switch (authenticationType) {
52
+ case 'apiKey':
53
+ if (!apiKey) {
54
+ throw new Error(types_1.GraphQLAuthError.NO_API_KEY);
112
55
  }
113
- });
114
- });
115
- };
56
+ headers = {
57
+ 'X-Api-Key': apiKey,
58
+ };
59
+ break;
60
+ case 'iam':
61
+ const session = await amplify.Auth.fetchAuthSession();
62
+ if (session.credentials === undefined) {
63
+ throw new Error(types_1.GraphQLAuthError.NO_CREDENTIALS);
64
+ }
65
+ break;
66
+ case 'oidc':
67
+ case 'userPool':
68
+ try {
69
+ let token;
70
+ token = (await amplify.Auth.fetchAuthSession()).tokens?.accessToken.toString();
71
+ if (!token) {
72
+ throw new Error(types_1.GraphQLAuthError.NO_FEDERATED_JWT);
73
+ }
74
+ headers = {
75
+ Authorization: token,
76
+ };
77
+ }
78
+ catch (e) {
79
+ throw new Error(types_1.GraphQLAuthError.NO_CURRENT_USER);
80
+ }
81
+ break;
82
+ case 'lambda':
83
+ if (!additionalHeaders.Authorization) {
84
+ throw new Error(types_1.GraphQLAuthError.NO_AUTH_TOKEN);
85
+ }
86
+ headers = {
87
+ Authorization: additionalHeaders.Authorization,
88
+ };
89
+ break;
90
+ case 'none':
91
+ break;
92
+ default:
93
+ break;
94
+ }
95
+ return headers;
96
+ }
116
97
  /**
117
98
  * to get the operation type
118
99
  * @param operation
119
100
  */
120
- InternalGraphQLAPIClass.prototype.getGraphqlOperationType = function (operation) {
121
- var doc = (0, graphql_1.parse)(operation);
122
- var definitions = doc.definitions;
123
- var _a = tslib_1.__read(definitions, 1), operationType = _a[0].operation;
101
+ getGraphqlOperationType(operation) {
102
+ const doc = (0, graphql_1.parse)(operation);
103
+ const definitions = doc.definitions;
104
+ const [{ operation: operationType }] = definitions;
124
105
  return operationType;
125
- };
106
+ }
126
107
  /**
127
108
  * Executes a GraphQL operation
128
109
  *
@@ -130,14 +111,13 @@ var InternalGraphQLAPIClass = /** @class */ (function () {
130
111
  * @param [additionalHeaders] - headers to merge in after any `graphql_headers` set in the config
131
112
  * @returns An Observable if the query is a subscription query, else a promise of the graphql result.
132
113
  */
133
- InternalGraphQLAPIClass.prototype.graphql = function (amplify, _a, additionalHeaders, customUserAgentDetails) {
134
- var paramQuery = _a.query, _b = _a.variables, variables = _b === void 0 ? {} : _b, authMode = _a.authMode, authToken = _a.authToken;
135
- var query = typeof paramQuery === 'string'
114
+ graphql(amplify, { query: paramQuery, variables = {}, authMode, authToken }, additionalHeaders, customUserAgentDetails) {
115
+ const query = typeof paramQuery === 'string'
136
116
  ? (0, graphql_1.parse)(paramQuery)
137
117
  : (0, graphql_1.parse)((0, graphql_1.print)(paramQuery));
138
- var _c = tslib_1.__read(query.definitions.filter(function (def) { return def.kind === 'OperationDefinition'; }), 1), _d = _c[0], operationDef = _d === void 0 ? {} : _d;
139
- var operationType = operationDef.operation;
140
- var headers = additionalHeaders || {};
118
+ const [operationDef = {}] = query.definitions.filter(def => def.kind === 'OperationDefinition');
119
+ const { operation: operationType } = operationDef;
120
+ const headers = additionalHeaders || {};
141
121
  // if an authorization header is set, have the explicit authToken take precedence
142
122
  if (authToken) {
143
123
  headers.Authorization = authToken;
@@ -145,174 +125,152 @@ var InternalGraphQLAPIClass = /** @class */ (function () {
145
125
  switch (operationType) {
146
126
  case 'query':
147
127
  case 'mutation':
148
- var abortController = new AbortController();
149
- var responsePromise = this._graphql(amplify, { query: query, variables: variables, authMode: authMode }, headers, abortController, customUserAgentDetails);
128
+ const abortController = new AbortController();
129
+ let responsePromise;
130
+ if (isAmplifyInstance(amplify)) {
131
+ responsePromise = this._graphql(amplify, { query, variables, authMode }, headers, abortController, customUserAgentDetails);
132
+ }
133
+ else {
134
+ const wrapper = amplifyInstance => this._graphql(amplifyInstance, { query, variables, authMode }, headers, abortController, customUserAgentDetails);
135
+ responsePromise = amplify(wrapper);
136
+ }
150
137
  this._api.updateRequestToBeCancellable(responsePromise, abortController);
151
138
  return responsePromise;
152
139
  case 'subscription':
153
- return this._graphqlSubscribe(amplify, { query: query, variables: variables, authMode: authMode }, headers, customUserAgentDetails);
140
+ return this._graphqlSubscribe(amplify, { query, variables, authMode }, headers, customUserAgentDetails);
154
141
  default:
155
- throw new Error("invalid operation type: ".concat(operationType));
142
+ throw new Error(`invalid operation type: ${operationType}`);
156
143
  }
157
- };
158
- InternalGraphQLAPIClass.prototype._graphql = function (amplify, _a, additionalHeaders, abortController, customUserAgentDetails) {
159
- var query = _a.query, variables = _a.variables, authMode = _a.authMode;
160
- if (additionalHeaders === void 0) { additionalHeaders = {}; }
161
- return tslib_1.__awaiter(this, void 0, void 0, function () {
162
- var _b, region, appSyncGraphqlEndpoint, customEndpoint, customEndpointRegion, _c, customHeaders, withCredentials, headers, _d, _e, _f, _g, _h, _j, _k, body, signingServiceInfo, endpoint, error, response, responseBody, result, err_1, errors;
163
- var _l;
164
- return tslib_1.__generator(this, function (_m) {
165
- switch (_m.label) {
166
- case 0:
167
- _b = (0, utils_2.resolveConfig)(amplify), region = _b.region, appSyncGraphqlEndpoint = _b.endpoint, customEndpoint = _b.customEndpoint, customEndpointRegion = _b.customEndpointRegion;
168
- _c = (0, utils_2.resolveLibraryOptions)(amplify), customHeaders = _c.headers, withCredentials = _c.withCredentials;
169
- _d = [{}];
170
- _e = !customEndpoint;
171
- if (!_e) return [3 /*break*/, 2];
172
- return [4 /*yield*/, this._headerBasedAuth(amplify, authMode, additionalHeaders)];
173
- case 1:
174
- _e = (_m.sent());
175
- _m.label = 2;
176
- case 2:
177
- _f = [tslib_1.__assign.apply(void 0, _d.concat([(_e)]))];
178
- _g = customEndpoint;
179
- if (!_g) return [3 /*break*/, 6];
180
- if (!customEndpointRegion) return [3 /*break*/, 4];
181
- return [4 /*yield*/, this._headerBasedAuth(amplify, authMode, additionalHeaders)];
182
- case 3:
183
- _h = _m.sent();
184
- return [3 /*break*/, 5];
185
- case 4:
186
- _h = {};
187
- _m.label = 5;
188
- case 5:
189
- _g = (_h);
190
- _m.label = 6;
191
- case 6:
192
- _j = [tslib_1.__assign.apply(void 0, _f.concat([((_g) ||
193
- {})]))];
194
- _k = customHeaders;
195
- if (!_k) return [3 /*break*/, 8];
196
- return [4 /*yield*/, customHeaders({
197
- query: (0, graphql_1.print)(query),
198
- variables: variables,
199
- })];
200
- case 7:
201
- _k = (_m.sent());
202
- _m.label = 8;
203
- case 8:
204
- headers = tslib_1.__assign.apply(void 0, [tslib_1.__assign.apply(void 0, [tslib_1.__assign.apply(void 0, _j.concat([(_k)])), additionalHeaders]), (!customEndpoint && (_l = {},
205
- _l[USER_AGENT_HEADER] = (0, utils_1.getAmplifyUserAgent)(customUserAgentDetails),
206
- _l))]);
207
- body = {
208
- query: (0, graphql_1.print)(query),
209
- variables: variables || null,
210
- };
211
- /**
212
- * We do not send the signing service info to the REST API under the
213
- * following conditions (i.e. it will not sign the request):
214
- * - there is a custom endpoint but no region
215
- * - the auth mode is `none`, or `apiKey`
216
- * - the auth mode is a type other than the types listed below
217
- */
218
- if ((customEndpoint && !customEndpointRegion) ||
219
- (authMode !== 'oidc' &&
220
- authMode !== 'userPool' &&
221
- authMode !== 'iam' &&
222
- authMode !== 'lambda')) {
223
- signingServiceInfo = null;
224
- }
225
- else {
226
- signingServiceInfo = {
227
- service: !customEndpointRegion ? 'appsync' : 'execute-api',
228
- region: !customEndpointRegion ? region : customEndpointRegion,
229
- };
230
- }
231
- endpoint = customEndpoint || appSyncGraphqlEndpoint;
232
- if (!endpoint) {
233
- error = new graphql_1.GraphQLError('No graphql endpoint provided.');
234
- throw {
235
- data: {},
236
- errors: [error],
237
- };
238
- }
239
- _m.label = 9;
240
- case 9:
241
- _m.trys.push([9, 12, , 13]);
242
- return [4 /*yield*/, this._api.post({
243
- url: new utils_1.AmplifyUrl(endpoint),
244
- options: {
245
- headers: headers,
246
- body: body,
247
- signingServiceInfo: signingServiceInfo,
248
- withCredentials: withCredentials,
249
- },
250
- abortController: abortController,
251
- })];
252
- case 10:
253
- responseBody = (_m.sent()).body;
254
- return [4 /*yield*/, responseBody.json()];
255
- case 11:
256
- result = _m.sent();
257
- response = result;
258
- return [3 /*break*/, 13];
259
- case 12:
260
- err_1 = _m.sent();
261
- // If the exception is because user intentionally
262
- // cancelled the request, do not modify the exception
263
- // so that clients can identify the exception correctly.
264
- if (this._api.isCancelErrorREST(err_1)) {
265
- throw err_1;
266
- }
267
- response = {
268
- data: {},
269
- errors: [new graphql_1.GraphQLError(err_1.message, null, null, null, null, err_1)],
270
- };
271
- return [3 /*break*/, 13];
272
- case 13:
273
- errors = response.errors;
274
- if (errors && errors.length) {
275
- throw response;
276
- }
277
- return [2 /*return*/, response];
278
- }
144
+ }
145
+ async _graphql(amplify, { query, variables, authMode }, additionalHeaders = {}, abortController, customUserAgentDetails) {
146
+ const { region: region, endpoint: appSyncGraphqlEndpoint, customEndpoint, customEndpointRegion, } = (0, utils_2.resolveConfig)(amplify);
147
+ // Retrieve library options from Amplify configuration
148
+ const { headers: customHeaders, withCredentials } = (0, utils_2.resolveLibraryOptions)(amplify);
149
+ // TODO: Figure what we need to do to remove `!`'s.
150
+ const headers = {
151
+ ...(!customEndpoint &&
152
+ (await this._headerBasedAuth(amplify, authMode, additionalHeaders))),
153
+ /**
154
+ * Custom endpoint headers.
155
+ * If there is both a custom endpoint and custom region present, we get the headers.
156
+ * If there is a custom endpoint but no region, we return an empty object.
157
+ * If neither are present, we return an empty object.
158
+ */
159
+ ...((customEndpoint &&
160
+ (customEndpointRegion
161
+ ? await this._headerBasedAuth(amplify, authMode, additionalHeaders)
162
+ : {})) ||
163
+ {}),
164
+ // Custom headers included in Amplify configuration options:
165
+ ...(customHeaders &&
166
+ (await customHeaders({
167
+ query: (0, graphql_1.print)(query),
168
+ variables,
169
+ }))),
170
+ // Headers from individual calls to `graphql`:
171
+ ...additionalHeaders,
172
+ // User agent headers:
173
+ ...(!customEndpoint && {
174
+ [USER_AGENT_HEADER]: (0, utils_1.getAmplifyUserAgent)(customUserAgentDetails),
175
+ }),
176
+ };
177
+ const body = {
178
+ query: (0, graphql_1.print)(query),
179
+ variables: variables || null,
180
+ };
181
+ let signingServiceInfo;
182
+ /**
183
+ * We do not send the signing service info to the REST API under the
184
+ * following conditions (i.e. it will not sign the request):
185
+ * - there is a custom endpoint but no region
186
+ * - the auth mode is `none`, or `apiKey`
187
+ * - the auth mode is a type other than the types listed below
188
+ */
189
+ if ((customEndpoint && !customEndpointRegion) ||
190
+ (authMode !== 'oidc' &&
191
+ authMode !== 'userPool' &&
192
+ authMode !== 'iam' &&
193
+ authMode !== 'lambda')) {
194
+ signingServiceInfo = null;
195
+ }
196
+ else {
197
+ signingServiceInfo = {
198
+ service: !customEndpointRegion ? 'appsync' : 'execute-api',
199
+ region: !customEndpointRegion ? region : customEndpointRegion,
200
+ };
201
+ }
202
+ const endpoint = customEndpoint || appSyncGraphqlEndpoint;
203
+ if (!endpoint) {
204
+ const error = new graphql_1.GraphQLError('No graphql endpoint provided.');
205
+ throw {
206
+ data: {},
207
+ errors: [error],
208
+ };
209
+ }
210
+ let response;
211
+ try {
212
+ const { body: responseBody } = await this._api.post({
213
+ url: new utils_1.AmplifyUrl(endpoint),
214
+ options: {
215
+ headers,
216
+ body,
217
+ signingServiceInfo,
218
+ withCredentials,
219
+ },
220
+ abortController,
279
221
  });
280
- });
281
- };
222
+ const result = await responseBody.json();
223
+ response = result;
224
+ }
225
+ catch (err) {
226
+ // If the exception is because user intentionally
227
+ // cancelled the request, do not modify the exception
228
+ // so that clients can identify the exception correctly.
229
+ if (this.isCancelError(err)) {
230
+ throw err;
231
+ }
232
+ response = {
233
+ data: {},
234
+ errors: [new graphql_1.GraphQLError(err.message, null, null, null, null, err)],
235
+ };
236
+ }
237
+ const { errors } = response;
238
+ if (errors && errors.length) {
239
+ throw response;
240
+ }
241
+ return response;
242
+ }
282
243
  /**
283
244
  * Checks to see if an error thrown is from an api request cancellation
284
245
  * @param {any} error - Any error
285
246
  * @return {boolean} - A boolean indicating if the error was from an api request cancellation
286
247
  */
287
- InternalGraphQLAPIClass.prototype.isCancelError = function (error) {
248
+ isCancelError(error) {
288
249
  return this._api.isCancelErrorREST(error);
289
- };
250
+ }
290
251
  /**
291
252
  * Cancels an inflight request. Only applicable for graphql queries and mutations
292
253
  * @param {any} request - request to cancel
293
254
  * @returns - A boolean indicating if the request was cancelled
294
255
  */
295
- InternalGraphQLAPIClass.prototype.cancel = function (request, message) {
256
+ cancel(request, message) {
296
257
  return this._api.cancelREST(request, message);
297
- };
298
- InternalGraphQLAPIClass.prototype._graphqlSubscribe = function (amplify, _a, additionalHeaders, customUserAgentDetails) {
299
- var query = _a.query, variables = _a.variables, authMode = _a.authMode;
300
- if (additionalHeaders === void 0) { additionalHeaders = {}; }
301
- var config = (0, utils_2.resolveConfig)(amplify);
258
+ }
259
+ _graphqlSubscribe(amplify, { query, variables, authMode }, additionalHeaders = {}, customUserAgentDetails) {
260
+ const config = (0, utils_2.resolveConfig)(amplify);
302
261
  if (!this.appSyncRealTime) {
303
262
  this.appSyncRealTime = new AWSAppSyncRealTimeProvider_1.AWSAppSyncRealTimeProvider();
304
263
  }
305
264
  return this.appSyncRealTime.subscribe({
306
265
  query: (0, graphql_1.print)(query),
307
- variables: variables,
308
- appSyncGraphqlEndpoint: config === null || config === void 0 ? void 0 : config.endpoint,
309
- region: config === null || config === void 0 ? void 0 : config.region,
310
- authenticationType: authMode || (config === null || config === void 0 ? void 0 : config.defaultAuthMode),
311
- apiKey: config === null || config === void 0 ? void 0 : config.apiKey,
312
- additionalHeaders: additionalHeaders,
266
+ variables,
267
+ appSyncGraphqlEndpoint: config?.endpoint,
268
+ region: config?.region,
269
+ authenticationType: authMode || config?.defaultAuthMode,
270
+ apiKey: config?.apiKey,
271
+ additionalHeaders,
313
272
  }, customUserAgentDetails);
314
- };
315
- return InternalGraphQLAPIClass;
316
- }());
273
+ }
274
+ }
317
275
  exports.InternalGraphQLAPIClass = InternalGraphQLAPIClass;
318
276
  exports.InternalGraphQLAPI = new InternalGraphQLAPIClass(null);
@@ -1,9 +1,11 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.generateClient = void 0;
4
- var v6_1 = require("./v6");
5
- var generateModelsProperty_1 = require("./generateModelsProperty");
6
- var types_1 = require("../types");
4
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
5
+ // SPDX-License-Identifier: Apache-2.0
6
+ const v6_1 = require("./v6");
7
+ const generateModelsProperty_1 = require("./generateModelsProperty");
8
+ const types_1 = require("../types");
7
9
  /**
8
10
  * @private
9
11
  *
@@ -14,16 +16,15 @@ var types_1 = require("../types");
14
16
  * @returns
15
17
  */
16
18
  function generateClient(params) {
17
- var _a;
18
- var client = (_a = {},
19
- _a[types_1.__amplify] = params.amplify,
20
- _a[types_1.__authMode] = params.authMode,
21
- _a[types_1.__authToken] = params.authToken,
22
- _a.graphql = v6_1.graphql,
23
- _a.cancel = v6_1.cancel,
24
- _a.isCancelError = v6_1.isCancelError,
25
- _a.models = {},
26
- _a);
19
+ const client = {
20
+ [types_1.__amplify]: params.amplify,
21
+ [types_1.__authMode]: params.authMode,
22
+ [types_1.__authToken]: params.authToken,
23
+ graphql: v6_1.graphql,
24
+ cancel: v6_1.cancel,
25
+ isCancelError: v6_1.isCancelError,
26
+ models: {},
27
+ };
27
28
  client.models = (0, generateModelsProperty_1.generateModelsProperty)(client, params);
28
29
  return client;
29
30
  }