@aws-amplify/api-graphql 3.4.12-api-v6-models.b3abc9b.0 → 4.0.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 (118) hide show
  1. package/README.md +3 -0
  2. package/lib/GraphQLAPI.d.ts +17 -4
  3. package/lib/GraphQLAPI.js +33 -27
  4. package/lib/Providers/AWSAppSyncRealTimeProvider/index.d.ts +64 -0
  5. package/lib/Providers/AWSAppSyncRealTimeProvider/index.js +690 -0
  6. package/lib/Providers/constants.d.ts +95 -0
  7. package/lib/Providers/constants.js +103 -0
  8. package/lib/index.d.ts +1 -3
  9. package/lib/index.js +6 -10
  10. package/lib/internals/InternalGraphQLAPI.d.ts +11 -34
  11. package/lib/internals/InternalGraphQLAPI.js +219 -345
  12. package/lib/internals/index.d.ts +1 -1
  13. package/lib/internals/index.js +2 -1
  14. package/lib/internals/v6.d.ts +14 -2
  15. package/lib/internals/v6.js +21 -3
  16. package/lib/tsconfig.tsbuildinfo +6813 -0
  17. package/lib/types/PubSub.d.ts +27 -0
  18. package/lib/types/PubSub.js +46 -0
  19. package/lib/types/index.d.ts +119 -12
  20. package/lib/types/index.js +4 -3
  21. package/lib/utils/ConnectionStateMonitor.d.ts +41 -0
  22. package/lib/utils/ConnectionStateMonitor.js +131 -0
  23. package/lib/utils/ReachabilityMonitor/index.d.ts +1 -0
  24. package/lib/utils/ReachabilityMonitor/index.js +6 -0
  25. package/lib/utils/ReachabilityMonitor/index.native.d.ts +1 -0
  26. package/lib/utils/ReachabilityMonitor/index.native.js +8 -0
  27. package/lib/utils/ReconnectionMonitor.d.ts +29 -0
  28. package/lib/utils/ReconnectionMonitor.js +68 -0
  29. package/lib/utils/errors/APIError.d.ts +7 -0
  30. package/lib/utils/errors/APIError.js +18 -0
  31. package/lib/utils/errors/assertValidationError.d.ts +5 -0
  32. package/lib/utils/errors/assertValidationError.js +16 -0
  33. package/lib/utils/errors/index.d.ts +3 -0
  34. package/lib/utils/errors/index.js +11 -0
  35. package/lib/utils/errors/validation.d.ts +7 -0
  36. package/lib/utils/errors/validation.js +25 -0
  37. package/lib/utils/index.d.ts +2 -0
  38. package/lib/utils/index.js +8 -0
  39. package/lib/utils/resolveConfig.d.ts +12 -0
  40. package/lib/utils/resolveConfig.js +22 -0
  41. package/lib/utils/resolveLibraryOptions.d.ts +11 -0
  42. package/lib/utils/resolveLibraryOptions.js +12 -0
  43. package/lib-esm/GraphQLAPI.d.ts +17 -4
  44. package/lib-esm/GraphQLAPI.js +33 -28
  45. package/lib-esm/Providers/AWSAppSyncRealTimeProvider/index.d.ts +64 -0
  46. package/lib-esm/Providers/AWSAppSyncRealTimeProvider/index.js +687 -0
  47. package/lib-esm/Providers/constants.d.ts +95 -0
  48. package/lib-esm/Providers/constants.js +100 -0
  49. package/lib-esm/index.d.ts +1 -3
  50. package/lib-esm/index.js +1 -4
  51. package/lib-esm/internals/InternalGraphQLAPI.d.ts +11 -34
  52. package/lib-esm/internals/InternalGraphQLAPI.js +218 -345
  53. package/lib-esm/internals/index.d.ts +1 -1
  54. package/lib-esm/internals/index.js +1 -2
  55. package/lib-esm/internals/v6.d.ts +14 -2
  56. package/lib-esm/internals/v6.js +18 -2
  57. package/lib-esm/tsconfig.tsbuildinfo +6813 -0
  58. package/lib-esm/types/PubSub.d.ts +27 -0
  59. package/lib-esm/types/PubSub.js +44 -0
  60. package/lib-esm/types/index.d.ts +119 -12
  61. package/lib-esm/types/index.js +2 -3
  62. package/lib-esm/utils/ConnectionStateMonitor.d.ts +41 -0
  63. package/lib-esm/utils/ConnectionStateMonitor.js +128 -0
  64. package/lib-esm/utils/ReachabilityMonitor/index.d.ts +1 -0
  65. package/lib-esm/utils/ReachabilityMonitor/index.js +4 -0
  66. package/lib-esm/utils/ReachabilityMonitor/index.native.d.ts +1 -0
  67. package/lib-esm/utils/ReachabilityMonitor/index.native.js +5 -0
  68. package/lib-esm/utils/ReconnectionMonitor.d.ts +29 -0
  69. package/lib-esm/utils/ReconnectionMonitor.js +65 -0
  70. package/lib-esm/utils/errors/APIError.d.ts +7 -0
  71. package/lib-esm/utils/errors/APIError.js +15 -0
  72. package/lib-esm/utils/errors/assertValidationError.d.ts +5 -0
  73. package/lib-esm/utils/errors/assertValidationError.js +13 -0
  74. package/lib-esm/utils/errors/index.d.ts +3 -0
  75. package/lib-esm/utils/errors/index.js +5 -0
  76. package/lib-esm/utils/errors/validation.d.ts +7 -0
  77. package/lib-esm/utils/errors/validation.js +23 -0
  78. package/lib-esm/utils/index.d.ts +2 -0
  79. package/lib-esm/utils/index.js +4 -0
  80. package/lib-esm/utils/resolveConfig.d.ts +12 -0
  81. package/lib-esm/utils/resolveConfig.js +20 -0
  82. package/lib-esm/utils/resolveLibraryOptions.d.ts +11 -0
  83. package/lib-esm/utils/resolveLibraryOptions.js +10 -0
  84. package/package.json +122 -118
  85. package/src/GraphQLAPI.ts +26 -4
  86. package/src/Providers/AWSAppSyncRealTimeProvider/index.ts +998 -0
  87. package/src/Providers/constants.ts +110 -0
  88. package/src/index.ts +2 -3
  89. package/src/internals/InternalGraphQLAPI.ts +181 -218
  90. package/src/internals/index.ts +1 -1
  91. package/src/internals/v6.ts +34 -2
  92. package/src/types/PubSub.ts +56 -0
  93. package/src/types/index.ts +175 -15
  94. package/src/utils/ConnectionStateMonitor.ts +199 -0
  95. package/src/utils/ReachabilityMonitor/index.native.ts +7 -0
  96. package/src/utils/ReachabilityMonitor/index.ts +4 -0
  97. package/src/utils/ReconnectionMonitor.ts +76 -0
  98. package/src/utils/errors/APIError.ts +21 -0
  99. package/src/utils/errors/assertValidationError.ts +19 -0
  100. package/src/utils/errors/index.ts +6 -0
  101. package/src/utils/errors/validation.ts +26 -0
  102. package/src/utils/index.ts +5 -0
  103. package/src/utils/resolveConfig.ts +35 -0
  104. package/src/utils/resolveLibraryOptions.ts +13 -0
  105. package/lib/.tsbuildinfo +0 -3
  106. package/lib/GraphQLAPI.js.map +0 -1
  107. package/lib/index.js.map +0 -1
  108. package/lib/internals/InternalGraphQLAPI.js.map +0 -1
  109. package/lib/internals/index.js.map +0 -1
  110. package/lib/internals/v6.js.map +0 -1
  111. package/lib/types/index.js.map +0 -1
  112. package/lib-esm/.tsbuildinfo +0 -3
  113. package/lib-esm/GraphQLAPI.js.map +0 -1
  114. package/lib-esm/index.js.map +0 -1
  115. package/lib-esm/internals/InternalGraphQLAPI.js.map +0 -1
  116. package/lib-esm/internals/index.js.map +0 -1
  117. package/lib-esm/internals/v6.js.map +0 -1
  118. package/lib-esm/types/index.js.map +0 -1
@@ -1,188 +1,107 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- var tslib_1 = require("tslib");
4
3
  // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
5
4
  // SPDX-License-Identifier: Apache-2.0
6
- var graphql_1 = require("graphql");
7
- var core_1 = require("@aws-amplify/core");
8
- var internals_1 = require("@aws-amplify/pubsub/internals");
9
- var auth_1 = require("@aws-amplify/auth");
10
- var cache_1 = require("@aws-amplify/cache");
11
- var types_1 = require("../types");
12
- var api_rest_1 = require("@aws-amplify/api-rest");
13
- var USER_AGENT_HEADER = 'x-amz-user-agent';
14
- var logger = new core_1.ConsoleLogger('GraphQLAPI');
15
- exports.graphqlOperation = function (query, variables, authToken) {
16
- if (variables === void 0) { variables = {}; }
17
- return ({
18
- query: query,
19
- variables: variables,
20
- authToken: authToken,
21
- });
5
+ const graphql_1 = require("graphql");
6
+ const core_1 = require("@aws-amplify/core");
7
+ const utils_1 = require("@aws-amplify/core/internals/utils");
8
+ const types_1 = require("../types");
9
+ const api_rest_1 = require("@aws-amplify/api-rest");
10
+ const internals_1 = require("@aws-amplify/api-rest/internals");
11
+ const AWSAppSyncRealTimeProvider_1 = require("../Providers/AWSAppSyncRealTimeProvider");
12
+ const utils_2 = require("../utils");
13
+ const USER_AGENT_HEADER = 'x-amz-user-agent';
14
+ const logger = new core_1.ConsoleLogger('GraphQLAPI');
15
+ exports.graphqlOperation = (query, variables = {}, authToken) => ({
16
+ query,
17
+ variables,
18
+ authToken,
19
+ });
20
+ const isAmplifyInstance = (amplify) => {
21
+ return typeof amplify !== 'function';
22
22
  };
23
23
  /**
24
24
  * Export Cloud Logic APIs
25
25
  */
26
- var InternalGraphQLAPIClass = /** @class */ (function () {
26
+ class InternalGraphQLAPIClass {
27
27
  /**
28
28
  * Initialize GraphQL API with AWS configuration
29
29
  * @param {Object} options - Configuration object for API
30
30
  */
31
- function InternalGraphQLAPIClass(options) {
32
- this._api = null;
33
- this.Auth = auth_1.Auth;
34
- this.Cache = cache_1.Cache;
35
- this.Credentials = core_1.Credentials;
31
+ constructor(options) {
32
+ this._api = {
33
+ post: internals_1.post,
34
+ cancelREST: internals_1.cancel,
35
+ isCancelErrorREST: api_rest_1.isCancelError,
36
+ updateRequestToBeCancellable: internals_1.updateRequestToBeCancellable,
37
+ };
36
38
  this._options = options;
37
39
  logger.debug('API Options', this._options);
38
40
  }
39
- InternalGraphQLAPIClass.prototype.getModuleName = function () {
41
+ getModuleName() {
40
42
  return 'InternalGraphQLAPI';
41
- };
42
- /**
43
- * Configure API
44
- * @param {Object} config - Configuration of the API
45
- * @return {Object} - The current configuration
46
- */
47
- InternalGraphQLAPIClass.prototype.configure = function (options) {
48
- var _a = options || {}, _b = _a.API, API = _b === void 0 ? {} : _b, otherOptions = tslib_1.__rest(_a, ["API"]);
49
- var opt = tslib_1.__assign(tslib_1.__assign({}, otherOptions), API);
50
- logger.debug('configure GraphQL API', { opt: opt });
51
- if (opt['aws_project_region']) {
52
- opt = Object.assign({}, opt, {
53
- region: opt['aws_project_region'],
54
- header: {},
55
- });
56
- }
57
- if (typeof opt.graphql_headers !== 'undefined' &&
58
- typeof opt.graphql_headers !== 'function') {
59
- logger.warn('graphql_headers should be a function');
60
- opt.graphql_headers = undefined;
61
- }
62
- this._options = Object.assign({}, this._options, opt);
63
- this.createInstance();
64
- return this._options;
65
- };
66
- /**
67
- * Create an instance of API for the library
68
- * @return - A promise of true if Success
69
- */
70
- InternalGraphQLAPIClass.prototype.createInstance = function () {
71
- logger.debug('create Rest instance');
72
- if (this._options) {
73
- this._api = new api_rest_1.RestClient(this._options);
74
- // Share instance Credentials with client for SSR
75
- this._api.Credentials = this.Credentials;
76
- return true;
77
- }
78
- else {
79
- return Promise.reject('API not configured');
80
- }
81
- };
82
- InternalGraphQLAPIClass.prototype._headerBasedAuth = function (defaultAuthenticationType, additionalHeaders) {
83
- if (additionalHeaders === void 0) { additionalHeaders = {}; }
84
- return tslib_1.__awaiter(this, void 0, void 0, function () {
85
- var _a, aws_appsync_authenticationType, apiKey, authenticationType, headers, _b, credentialsOK, token, federatedInfo, currentUser, e_1, session, e_2;
86
- return tslib_1.__generator(this, function (_c) {
87
- switch (_c.label) {
88
- case 0:
89
- _a = this._options, aws_appsync_authenticationType = _a.aws_appsync_authenticationType, apiKey = _a.aws_appsync_apiKey;
90
- authenticationType = defaultAuthenticationType || aws_appsync_authenticationType || 'AWS_IAM';
91
- headers = {};
92
- _b = authenticationType;
93
- switch (_b) {
94
- case 'API_KEY': return [3 /*break*/, 1];
95
- case 'AWS_IAM': return [3 /*break*/, 2];
96
- case 'OPENID_CONNECT': return [3 /*break*/, 4];
97
- case 'AMAZON_COGNITO_USER_POOLS': return [3 /*break*/, 11];
98
- case 'AWS_LAMBDA': return [3 /*break*/, 15];
99
- }
100
- return [3 /*break*/, 16];
101
- case 1:
102
- if (!apiKey) {
103
- throw new Error(types_1.GraphQLAuthError.NO_API_KEY);
104
- }
105
- headers = {
106
- Authorization: null,
107
- 'X-Api-Key': apiKey,
108
- };
109
- return [3 /*break*/, 17];
110
- case 2: return [4 /*yield*/, this._ensureCredentials()];
111
- case 3:
112
- credentialsOK = _c.sent();
113
- if (!credentialsOK) {
114
- throw new Error(types_1.GraphQLAuthError.NO_CREDENTIALS);
115
- }
116
- return [3 /*break*/, 17];
117
- case 4:
118
- _c.trys.push([4, 9, , 10]);
119
- token = void 0;
120
- return [4 /*yield*/, cache_1.Cache.getItem('federatedInfo')];
121
- case 5:
122
- federatedInfo = _c.sent();
123
- if (!federatedInfo) return [3 /*break*/, 6];
124
- token = federatedInfo.token;
125
- return [3 /*break*/, 8];
126
- case 6: return [4 /*yield*/, auth_1.Auth.currentAuthenticatedUser()];
127
- case 7:
128
- currentUser = _c.sent();
129
- if (currentUser) {
130
- token = currentUser.token;
131
- }
132
- _c.label = 8;
133
- case 8:
134
- if (!token) {
135
- throw new Error(types_1.GraphQLAuthError.NO_FEDERATED_JWT);
136
- }
137
- headers = {
138
- Authorization: token,
139
- };
140
- return [3 /*break*/, 10];
141
- case 9:
142
- e_1 = _c.sent();
143
- throw new Error(types_1.GraphQLAuthError.NO_CURRENT_USER);
144
- case 10: return [3 /*break*/, 17];
145
- case 11:
146
- _c.trys.push([11, 13, , 14]);
147
- return [4 /*yield*/, this.Auth.currentSession()];
148
- case 12:
149
- session = _c.sent();
150
- headers = {
151
- Authorization: session.getAccessToken().getJwtToken(),
152
- };
153
- return [3 /*break*/, 14];
154
- case 13:
155
- e_2 = _c.sent();
156
- throw new Error(types_1.GraphQLAuthError.NO_CURRENT_USER);
157
- case 14: return [3 /*break*/, 17];
158
- case 15:
159
- if (!additionalHeaders.Authorization) {
160
- throw new Error(types_1.GraphQLAuthError.NO_AUTH_TOKEN);
161
- }
162
- headers = {
163
- Authorization: additionalHeaders.Authorization,
164
- };
165
- return [3 /*break*/, 17];
166
- case 16:
167
- headers = {
168
- Authorization: null,
169
- };
170
- return [3 /*break*/, 17];
171
- case 17: return [2 /*return*/, headers];
43
+ }
44
+ async _headerBasedAuth(amplify, authMode, additionalHeaders = {}) {
45
+ const config = amplify.getConfig();
46
+ const { region: region, endpoint: appSyncGraphqlEndpoint, apiKey, defaultAuthMode, } = utils_2.resolveConfig(amplify);
47
+ const authenticationType = authMode || defaultAuthMode || 'iam';
48
+ let headers = {};
49
+ switch (authenticationType) {
50
+ case 'apiKey':
51
+ if (!apiKey) {
52
+ throw new Error(types_1.GraphQLAuthError.NO_API_KEY);
172
53
  }
173
- });
174
- });
175
- };
54
+ headers = {
55
+ 'X-Api-Key': apiKey,
56
+ };
57
+ break;
58
+ case 'iam':
59
+ const session = await amplify.Auth.fetchAuthSession();
60
+ if (session.credentials === undefined) {
61
+ throw new Error(types_1.GraphQLAuthError.NO_CREDENTIALS);
62
+ }
63
+ break;
64
+ case 'oidc':
65
+ case 'userPool':
66
+ try {
67
+ let token;
68
+ token = (await amplify.Auth.fetchAuthSession()).tokens?.accessToken.toString();
69
+ if (!token) {
70
+ throw new Error(types_1.GraphQLAuthError.NO_FEDERATED_JWT);
71
+ }
72
+ headers = {
73
+ Authorization: token,
74
+ };
75
+ }
76
+ catch (e) {
77
+ throw new Error(types_1.GraphQLAuthError.NO_CURRENT_USER);
78
+ }
79
+ break;
80
+ case 'lambda':
81
+ if (!additionalHeaders.Authorization) {
82
+ throw new Error(types_1.GraphQLAuthError.NO_AUTH_TOKEN);
83
+ }
84
+ headers = {
85
+ Authorization: additionalHeaders.Authorization,
86
+ };
87
+ break;
88
+ case 'none':
89
+ break;
90
+ default:
91
+ break;
92
+ }
93
+ return headers;
94
+ }
176
95
  /**
177
96
  * to get the operation type
178
97
  * @param operation
179
98
  */
180
- InternalGraphQLAPIClass.prototype.getGraphqlOperationType = function (operation) {
181
- var doc = graphql_1.parse(operation);
182
- var definitions = doc.definitions;
183
- var _a = tslib_1.__read(definitions, 1), operationType = _a[0].operation;
99
+ getGraphqlOperationType(operation) {
100
+ const doc = graphql_1.parse(operation);
101
+ const definitions = doc.definitions;
102
+ const [{ operation: operationType }] = definitions;
184
103
  return operationType;
185
- };
104
+ }
186
105
  /**
187
106
  * Executes a GraphQL operation
188
107
  *
@@ -190,14 +109,13 @@ var InternalGraphQLAPIClass = /** @class */ (function () {
190
109
  * @param [additionalHeaders] - headers to merge in after any `graphql_headers` set in the config
191
110
  * @returns An Observable if the query is a subscription query, else a promise of the graphql result.
192
111
  */
193
- InternalGraphQLAPIClass.prototype.graphql = function (_a, additionalHeaders, customUserAgentDetails) {
194
- var paramQuery = _a.query, _b = _a.variables, variables = _b === void 0 ? {} : _b, authMode = _a.authMode, authToken = _a.authToken;
195
- var query = typeof paramQuery === 'string'
112
+ graphql(amplify, { query: paramQuery, variables = {}, authMode, authToken }, additionalHeaders, customUserAgentDetails) {
113
+ const query = typeof paramQuery === 'string'
196
114
  ? graphql_1.parse(paramQuery)
197
115
  : graphql_1.parse(graphql_1.print(paramQuery));
198
- var _c = tslib_1.__read(query.definitions.filter(function (def) { return def.kind === 'OperationDefinition'; }), 1), _d = _c[0], operationDef = _d === void 0 ? {} : _d;
199
- var operationType = operationDef.operation;
200
- var headers = additionalHeaders || {};
116
+ const [operationDef = {}] = query.definitions.filter(def => def.kind === 'OperationDefinition');
117
+ const { operation: operationType } = operationDef;
118
+ const headers = additionalHeaders || {};
201
119
  // if an authorization header is set, have the explicit authToken take precedence
202
120
  if (authToken) {
203
121
  headers.Authorization = authToken;
@@ -205,196 +123,152 @@ var InternalGraphQLAPIClass = /** @class */ (function () {
205
123
  switch (operationType) {
206
124
  case 'query':
207
125
  case 'mutation':
208
- this.createInstanceIfNotCreated();
209
- var cancellableToken = this._api.getCancellableToken();
210
- var initParams = {
211
- cancellableToken: cancellableToken,
212
- withCredentials: this._options.withCredentials,
213
- };
214
- var responsePromise = this._graphql({ query: query, variables: variables, authMode: authMode }, headers, initParams, customUserAgentDetails);
215
- this._api.updateRequestToBeCancellable(responsePromise, cancellableToken);
126
+ const abortController = new AbortController();
127
+ let responsePromise;
128
+ if (isAmplifyInstance(amplify)) {
129
+ responsePromise = this._graphql(amplify, { query, variables, authMode }, headers, abortController, customUserAgentDetails);
130
+ }
131
+ else {
132
+ const wrapper = amplifyInstance => this._graphql(amplifyInstance, { query, variables, authMode }, headers, abortController, customUserAgentDetails);
133
+ responsePromise = amplify(wrapper);
134
+ }
135
+ this._api.updateRequestToBeCancellable(responsePromise, abortController);
216
136
  return responsePromise;
217
137
  case 'subscription':
218
- return this._graphqlSubscribe({ query: query, variables: variables, authMode: authMode }, headers, customUserAgentDetails);
138
+ return this._graphqlSubscribe(amplify, { query, variables, authMode }, headers, customUserAgentDetails);
219
139
  default:
220
- throw new Error("invalid operation type: " + operationType);
140
+ throw new Error(`invalid operation type: ${operationType}`);
221
141
  }
222
- };
223
- InternalGraphQLAPIClass.prototype._graphql = function (_a, additionalHeaders, initParams, customUserAgentDetails) {
224
- var query = _a.query, variables = _a.variables, authMode = _a.authMode;
225
- if (additionalHeaders === void 0) { additionalHeaders = {}; }
226
- if (initParams === void 0) { initParams = {}; }
227
- return tslib_1.__awaiter(this, void 0, void 0, function () {
228
- var _b, region, appSyncGraphqlEndpoint, _c, graphql_headers, customGraphqlEndpoint, customEndpointRegion, headers, _d, _e, _f, _g, _h, _j, body, init, endpoint, error, response, err_1, errors;
229
- var _k;
230
- return tslib_1.__generator(this, function (_l) {
231
- switch (_l.label) {
232
- case 0:
233
- this.createInstanceIfNotCreated();
234
- _b = this._options, region = _b.aws_appsync_region, appSyncGraphqlEndpoint = _b.aws_appsync_graphqlEndpoint, _c = _b.graphql_headers, graphql_headers = _c === void 0 ? function () { return ({}); } : _c, customGraphqlEndpoint = _b.graphql_endpoint, customEndpointRegion = _b.graphql_endpoint_iam_region;
235
- _d = [{}];
236
- _e = !customGraphqlEndpoint;
237
- if (!_e) return [3 /*break*/, 2];
238
- return [4 /*yield*/, this._headerBasedAuth(authMode, additionalHeaders)];
239
- case 1:
240
- _e = (_l.sent());
241
- _l.label = 2;
242
- case 2:
243
- _f = [tslib_1.__assign.apply(void 0, _d.concat([(_e)]))];
244
- _g = customGraphqlEndpoint;
245
- if (!_g) return [3 /*break*/, 6];
246
- if (!customEndpointRegion) return [3 /*break*/, 4];
247
- return [4 /*yield*/, this._headerBasedAuth(authMode, additionalHeaders)];
248
- case 3:
249
- _h = _l.sent();
250
- return [3 /*break*/, 5];
251
- case 4:
252
- _h = { Authorization: null };
253
- _l.label = 5;
254
- case 5:
255
- _g = (_h);
256
- _l.label = 6;
257
- case 6:
258
- _j = [tslib_1.__assign.apply(void 0, _f.concat([(_g)]))];
259
- return [4 /*yield*/, graphql_headers({ query: query, variables: variables })];
260
- case 7:
261
- headers = tslib_1.__assign.apply(void 0, [tslib_1.__assign.apply(void 0, [tslib_1.__assign.apply(void 0, _j.concat([(_l.sent())])), additionalHeaders]), (!customGraphqlEndpoint && (_k = {},
262
- _k[USER_AGENT_HEADER] = core_1.getAmplifyUserAgent(customUserAgentDetails),
263
- _k))]);
264
- body = {
265
- query: graphql_1.print(query),
266
- variables: variables,
267
- };
268
- init = Object.assign({
269
- headers: headers,
270
- body: body,
271
- signerServiceInfo: {
272
- service: !customGraphqlEndpoint ? 'appsync' : 'execute-api',
273
- region: !customGraphqlEndpoint ? region : customEndpointRegion,
274
- },
275
- }, initParams);
276
- endpoint = customGraphqlEndpoint || appSyncGraphqlEndpoint;
277
- if (!endpoint) {
278
- error = new graphql_1.GraphQLError('No graphql endpoint provided.');
279
- throw {
280
- data: {},
281
- errors: [error],
282
- };
283
- }
284
- _l.label = 8;
285
- case 8:
286
- _l.trys.push([8, 10, , 11]);
287
- return [4 /*yield*/, this._api.post(endpoint, init)];
288
- case 9:
289
- response = _l.sent();
290
- return [3 /*break*/, 11];
291
- case 10:
292
- err_1 = _l.sent();
293
- // If the exception is because user intentionally
294
- // cancelled the request, do not modify the exception
295
- // so that clients can identify the exception correctly.
296
- if (this._api.isCancel(err_1)) {
297
- throw err_1;
298
- }
299
- response = {
300
- data: {},
301
- errors: [new graphql_1.GraphQLError(err_1.message, null, null, null, null, err_1)],
302
- };
303
- return [3 /*break*/, 11];
304
- case 11:
305
- errors = response.errors;
306
- if (errors && errors.length) {
307
- throw response;
308
- }
309
- return [2 /*return*/, response];
310
- }
311
- });
312
- });
313
- };
314
- InternalGraphQLAPIClass.prototype.createInstanceIfNotCreated = function () {
315
- return tslib_1.__awaiter(this, void 0, void 0, function () {
316
- return tslib_1.__generator(this, function (_a) {
317
- switch (_a.label) {
318
- case 0:
319
- if (!!this._api) return [3 /*break*/, 2];
320
- return [4 /*yield*/, this.createInstance()];
321
- case 1:
322
- _a.sent();
323
- _a.label = 2;
324
- case 2: return [2 /*return*/];
325
- }
142
+ }
143
+ async _graphql(amplify, { query, variables, authMode }, additionalHeaders = {}, abortController, customUserAgentDetails) {
144
+ const { region: region, endpoint: appSyncGraphqlEndpoint, customEndpoint, customEndpointRegion, } = utils_2.resolveConfig(amplify);
145
+ // Retrieve library options from Amplify configuration
146
+ const { headers: customHeaders, withCredentials } = utils_2.resolveLibraryOptions(amplify);
147
+ // TODO: Figure what we need to do to remove `!`'s.
148
+ const headers = {
149
+ ...(!customEndpoint &&
150
+ (await this._headerBasedAuth(amplify, authMode, additionalHeaders))),
151
+ /**
152
+ * Custom endpoint headers.
153
+ * If there is both a custom endpoint and custom region present, we get the headers.
154
+ * If there is a custom endpoint but no region, we return an empty object.
155
+ * If neither are present, we return an empty object.
156
+ */
157
+ ...((customEndpoint &&
158
+ (customEndpointRegion
159
+ ? await this._headerBasedAuth(amplify, authMode, additionalHeaders)
160
+ : {})) ||
161
+ {}),
162
+ // Custom headers included in Amplify configuration options:
163
+ ...(customHeaders &&
164
+ (await customHeaders({
165
+ query: graphql_1.print(query),
166
+ variables,
167
+ }))),
168
+ // Headers from individual calls to `graphql`:
169
+ ...additionalHeaders,
170
+ // User agent headers:
171
+ ...(!customEndpoint && {
172
+ [USER_AGENT_HEADER]: utils_1.getAmplifyUserAgent(customUserAgentDetails),
173
+ }),
174
+ };
175
+ const body = {
176
+ query: graphql_1.print(query),
177
+ variables: variables || null,
178
+ };
179
+ let signingServiceInfo;
180
+ /**
181
+ * We do not send the signing service info to the REST API under the
182
+ * following conditions (i.e. it will not sign the request):
183
+ * - there is a custom endpoint but no region
184
+ * - the auth mode is `none`, or `apiKey`
185
+ * - the auth mode is a type other than the types listed below
186
+ */
187
+ if ((customEndpoint && !customEndpointRegion) ||
188
+ (authMode !== 'oidc' &&
189
+ authMode !== 'userPool' &&
190
+ authMode !== 'iam' &&
191
+ authMode !== 'lambda')) {
192
+ signingServiceInfo = null;
193
+ }
194
+ else {
195
+ signingServiceInfo = {
196
+ service: !customEndpointRegion ? 'appsync' : 'execute-api',
197
+ region: !customEndpointRegion ? region : customEndpointRegion,
198
+ };
199
+ }
200
+ const endpoint = customEndpoint || appSyncGraphqlEndpoint;
201
+ if (!endpoint) {
202
+ const error = new graphql_1.GraphQLError('No graphql endpoint provided.');
203
+ throw {
204
+ data: {},
205
+ errors: [error],
206
+ };
207
+ }
208
+ let response;
209
+ try {
210
+ const { body: responseBody } = await this._api.post({
211
+ url: new utils_1.AmplifyUrl(endpoint),
212
+ options: {
213
+ headers,
214
+ body,
215
+ signingServiceInfo,
216
+ withCredentials,
217
+ },
218
+ abortController,
326
219
  });
327
- });
328
- };
220
+ const result = await responseBody.json();
221
+ response = result;
222
+ }
223
+ catch (err) {
224
+ // If the exception is because user intentionally
225
+ // cancelled the request, do not modify the exception
226
+ // so that clients can identify the exception correctly.
227
+ if (this.isCancelError(err)) {
228
+ throw err;
229
+ }
230
+ response = {
231
+ data: {},
232
+ errors: [new graphql_1.GraphQLError(err.message, null, null, null, null, err)],
233
+ };
234
+ }
235
+ const { errors } = response;
236
+ if (errors && errors.length) {
237
+ throw response;
238
+ }
239
+ return response;
240
+ }
329
241
  /**
330
242
  * Checks to see if an error thrown is from an api request cancellation
331
243
  * @param {any} error - Any error
332
244
  * @return {boolean} - A boolean indicating if the error was from an api request cancellation
333
245
  */
334
- InternalGraphQLAPIClass.prototype.isCancel = function (error) {
335
- return this._api.isCancel(error);
336
- };
246
+ isCancelError(error) {
247
+ return this._api.isCancelErrorREST(error);
248
+ }
337
249
  /**
338
250
  * Cancels an inflight request. Only applicable for graphql queries and mutations
339
251
  * @param {any} request - request to cancel
340
- * @return {boolean} - A boolean indicating if the request was cancelled
252
+ * @returns - A boolean indicating if the request was cancelled
341
253
  */
342
- InternalGraphQLAPIClass.prototype.cancel = function (request, message) {
343
- return this._api.cancel(request, message);
344
- };
345
- /**
346
- * Check if the request has a corresponding cancel token in the WeakMap.
347
- * @params request - The request promise
348
- * @return if the request has a corresponding cancel token.
349
- */
350
- InternalGraphQLAPIClass.prototype.hasCancelToken = function (request) {
351
- return this._api.hasCancelToken(request);
352
- };
353
- InternalGraphQLAPIClass.prototype._graphqlSubscribe = function (_a, additionalHeaders, customUserAgentDetails) {
354
- var query = _a.query, variables = _a.variables, defaultAuthenticationType = _a.authMode, authToken = _a.authToken;
355
- if (additionalHeaders === void 0) { additionalHeaders = {}; }
356
- var _b = this._options, region = _b.aws_appsync_region, appSyncGraphqlEndpoint = _b.aws_appsync_graphqlEndpoint, aws_appsync_authenticationType = _b.aws_appsync_authenticationType, apiKey = _b.aws_appsync_apiKey, _c = _b.graphql_headers, graphql_headers = _c === void 0 ? function () { return ({}); } : _c;
357
- var authenticationType = defaultAuthenticationType || aws_appsync_authenticationType || 'AWS_IAM';
358
- if (internals_1.InternalPubSub && typeof internals_1.InternalPubSub.subscribe === 'function') {
359
- return internals_1.InternalPubSub.subscribe('', {
360
- provider: core_1.INTERNAL_AWS_APPSYNC_REALTIME_PUBSUB_PROVIDER,
361
- appSyncGraphqlEndpoint: appSyncGraphqlEndpoint,
362
- authenticationType: authenticationType,
363
- apiKey: apiKey,
364
- query: graphql_1.print(query),
365
- region: region,
366
- variables: variables,
367
- graphql_headers: graphql_headers,
368
- additionalHeaders: additionalHeaders,
369
- authToken: authToken,
370
- }, customUserAgentDetails);
371
- }
372
- else {
373
- logger.debug('No pubsub module applied for subscription');
374
- throw new Error('No pubsub module applied for subscription');
254
+ cancel(request, message) {
255
+ return this._api.cancelREST(request, message);
256
+ }
257
+ _graphqlSubscribe(amplify, { query, variables, authMode }, additionalHeaders = {}, customUserAgentDetails) {
258
+ const config = utils_2.resolveConfig(amplify);
259
+ if (!this.appSyncRealTime) {
260
+ this.appSyncRealTime = new AWSAppSyncRealTimeProvider_1.AWSAppSyncRealTimeProvider();
375
261
  }
376
- };
377
- /**
378
- * @private
379
- */
380
- InternalGraphQLAPIClass.prototype._ensureCredentials = function () {
381
- var _this = this;
382
- return this.Credentials.get()
383
- .then(function (credentials) {
384
- if (!credentials)
385
- return false;
386
- var cred = _this.Credentials.shear(credentials);
387
- logger.debug('set credentials for api', cred);
388
- return true;
389
- })
390
- .catch(function (err) {
391
- logger.warn('ensure credentials error', err);
392
- return false;
393
- });
394
- };
395
- return InternalGraphQLAPIClass;
396
- }());
262
+ return this.appSyncRealTime.subscribe({
263
+ query: graphql_1.print(query),
264
+ variables,
265
+ appSyncGraphqlEndpoint: config?.endpoint,
266
+ region: config?.region,
267
+ authenticationType: authMode ?? config?.defaultAuthMode,
268
+ apiKey: config?.apiKey,
269
+ additionalHeaders,
270
+ }, customUserAgentDetails);
271
+ }
272
+ }
397
273
  exports.InternalGraphQLAPIClass = InternalGraphQLAPIClass;
398
274
  exports.InternalGraphQLAPI = new InternalGraphQLAPIClass(null);
399
- core_1.Amplify.register(exports.InternalGraphQLAPI);
400
- //# sourceMappingURL=InternalGraphQLAPI.js.map
@@ -1,2 +1,2 @@
1
1
  export { InternalGraphQLAPI, InternalGraphQLAPIClass, } from './InternalGraphQLAPI';
2
- export { graphql } from './v6';
2
+ export { graphql, cancel, isCancelError } from './v6';
@@ -7,4 +7,5 @@ exports.InternalGraphQLAPI = InternalGraphQLAPI_1.InternalGraphQLAPI;
7
7
  exports.InternalGraphQLAPIClass = InternalGraphQLAPI_1.InternalGraphQLAPIClass;
8
8
  var v6_1 = require("./v6");
9
9
  exports.graphql = v6_1.graphql;
10
- //# sourceMappingURL=index.js.map
10
+ exports.cancel = v6_1.cancel;
11
+ exports.isCancelError = v6_1.isCancelError;