UNPKG

27.2 kBJavaScriptView Raw
1(function (global, factory) {
2 typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/core'), require('@angular/common/http'), require('@apollo/client/core'), require('graphql'), require('extract-files'), require('rxjs'), require('@apollo/client/link/batch')) :
3 typeof define === 'function' && define.amd ? define('apollo-angular/http', ['exports', '@angular/core', '@angular/common/http', '@apollo/client/core', 'graphql', 'extract-files', 'rxjs', '@apollo/client/link/batch'], factory) :
4 (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory((global.ngApollo = global.ngApollo || {}, global.ngApollo.http = {}), global.ng.core, global.ng.common.http, global.core, global.graphql, global.extractFiles, global.rxjs, global.batch));
5}(this, (function (exports, i0, i1, core, graphql, extractFiles, rxjs, batch) { 'use strict';
6
7 /*! *****************************************************************************
8 Copyright (c) Microsoft Corporation.
9
10 Permission to use, copy, modify, and/or distribute this software for any
11 purpose with or without fee is hereby granted.
12
13 THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
14 REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
15 AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
16 INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
17 LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
18 OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
19 PERFORMANCE OF THIS SOFTWARE.
20 ***************************************************************************** */
21 /* global Reflect, Promise */
22 var extendStatics = function (d, b) {
23 extendStatics = Object.setPrototypeOf ||
24 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
25 function (d, b) { for (var p in b)
26 if (b.hasOwnProperty(p))
27 d[p] = b[p]; };
28 return extendStatics(d, b);
29 };
30 function __extends(d, b) {
31 extendStatics(d, b);
32 function __() { this.constructor = d; }
33 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
34 }
35 var __assign = function () {
36 __assign = Object.assign || function __assign(t) {
37 for (var s, i = 1, n = arguments.length; i < n; i++) {
38 s = arguments[i];
39 for (var p in s)
40 if (Object.prototype.hasOwnProperty.call(s, p))
41 t[p] = s[p];
42 }
43 return t;
44 };
45 return __assign.apply(this, arguments);
46 };
47 function __rest(s, e) {
48 var t = {};
49 for (var p in s)
50 if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
51 t[p] = s[p];
52 if (s != null && typeof Object.getOwnPropertySymbols === "function")
53 for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
54 if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
55 t[p[i]] = s[p[i]];
56 }
57 return t;
58 }
59 function __decorate(decorators, target, key, desc) {
60 var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
61 if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
62 r = Reflect.decorate(decorators, target, key, desc);
63 else
64 for (var i = decorators.length - 1; i >= 0; i--)
65 if (d = decorators[i])
66 r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
67 return c > 3 && r && Object.defineProperty(target, key, r), r;
68 }
69 function __param(paramIndex, decorator) {
70 return function (target, key) { decorator(target, key, paramIndex); };
71 }
72 function __metadata(metadataKey, metadataValue) {
73 if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
74 return Reflect.metadata(metadataKey, metadataValue);
75 }
76 function __awaiter(thisArg, _arguments, P, generator) {
77 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
78 return new (P || (P = Promise))(function (resolve, reject) {
79 function fulfilled(value) { try {
80 step(generator.next(value));
81 }
82 catch (e) {
83 reject(e);
84 } }
85 function rejected(value) { try {
86 step(generator["throw"](value));
87 }
88 catch (e) {
89 reject(e);
90 } }
91 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
92 step((generator = generator.apply(thisArg, _arguments || [])).next());
93 });
94 }
95 function __generator(thisArg, body) {
96 var _ = { label: 0, sent: function () { if (t[0] & 1)
97 throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
98 return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function () { return this; }), g;
99 function verb(n) { return function (v) { return step([n, v]); }; }
100 function step(op) {
101 if (f)
102 throw new TypeError("Generator is already executing.");
103 while (_)
104 try {
105 if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done)
106 return t;
107 if (y = 0, t)
108 op = [op[0] & 2, t.value];
109 switch (op[0]) {
110 case 0:
111 case 1:
112 t = op;
113 break;
114 case 4:
115 _.label++;
116 return { value: op[1], done: false };
117 case 5:
118 _.label++;
119 y = op[1];
120 op = [0];
121 continue;
122 case 7:
123 op = _.ops.pop();
124 _.trys.pop();
125 continue;
126 default:
127 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
128 _ = 0;
129 continue;
130 }
131 if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) {
132 _.label = op[1];
133 break;
134 }
135 if (op[0] === 6 && _.label < t[1]) {
136 _.label = t[1];
137 t = op;
138 break;
139 }
140 if (t && _.label < t[2]) {
141 _.label = t[2];
142 _.ops.push(op);
143 break;
144 }
145 if (t[2])
146 _.ops.pop();
147 _.trys.pop();
148 continue;
149 }
150 op = body.call(thisArg, _);
151 }
152 catch (e) {
153 op = [6, e];
154 y = 0;
155 }
156 finally {
157 f = t = 0;
158 }
159 if (op[0] & 5)
160 throw op[1];
161 return { value: op[0] ? op[1] : void 0, done: true };
162 }
163 }
164 var __createBinding = Object.create ? (function (o, m, k, k2) {
165 if (k2 === undefined)
166 k2 = k;
167 Object.defineProperty(o, k2, { enumerable: true, get: function () { return m[k]; } });
168 }) : (function (o, m, k, k2) {
169 if (k2 === undefined)
170 k2 = k;
171 o[k2] = m[k];
172 });
173 function __exportStar(m, exports) {
174 for (var p in m)
175 if (p !== "default" && !exports.hasOwnProperty(p))
176 __createBinding(exports, m, p);
177 }
178 function __values(o) {
179 var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
180 if (m)
181 return m.call(o);
182 if (o && typeof o.length === "number")
183 return {
184 next: function () {
185 if (o && i >= o.length)
186 o = void 0;
187 return { value: o && o[i++], done: !o };
188 }
189 };
190 throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
191 }
192 function __read(o, n) {
193 var m = typeof Symbol === "function" && o[Symbol.iterator];
194 if (!m)
195 return o;
196 var i = m.call(o), r, ar = [], e;
197 try {
198 while ((n === void 0 || n-- > 0) && !(r = i.next()).done)
199 ar.push(r.value);
200 }
201 catch (error) {
202 e = { error: error };
203 }
204 finally {
205 try {
206 if (r && !r.done && (m = i["return"]))
207 m.call(i);
208 }
209 finally {
210 if (e)
211 throw e.error;
212 }
213 }
214 return ar;
215 }
216 function __spread() {
217 for (var ar = [], i = 0; i < arguments.length; i++)
218 ar = ar.concat(__read(arguments[i]));
219 return ar;
220 }
221 function __spreadArrays() {
222 for (var s = 0, i = 0, il = arguments.length; i < il; i++)
223 s += arguments[i].length;
224 for (var r = Array(s), k = 0, i = 0; i < il; i++)
225 for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
226 r[k] = a[j];
227 return r;
228 }
229 ;
230 function __await(v) {
231 return this instanceof __await ? (this.v = v, this) : new __await(v);
232 }
233 function __asyncGenerator(thisArg, _arguments, generator) {
234 if (!Symbol.asyncIterator)
235 throw new TypeError("Symbol.asyncIterator is not defined.");
236 var g = generator.apply(thisArg, _arguments || []), i, q = [];
237 return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
238 function verb(n) { if (g[n])
239 i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
240 function resume(n, v) { try {
241 step(g[n](v));
242 }
243 catch (e) {
244 settle(q[0][3], e);
245 } }
246 function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
247 function fulfill(value) { resume("next", value); }
248 function reject(value) { resume("throw", value); }
249 function settle(f, v) { if (f(v), q.shift(), q.length)
250 resume(q[0][0], q[0][1]); }
251 }
252 function __asyncDelegator(o) {
253 var i, p;
254 return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
255 function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; }
256 }
257 function __asyncValues(o) {
258 if (!Symbol.asyncIterator)
259 throw new TypeError("Symbol.asyncIterator is not defined.");
260 var m = o[Symbol.asyncIterator], i;
261 return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
262 function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
263 function settle(resolve, reject, d, v) { Promise.resolve(v).then(function (v) { resolve({ value: v, done: d }); }, reject); }
264 }
265 function __makeTemplateObject(cooked, raw) {
266 if (Object.defineProperty) {
267 Object.defineProperty(cooked, "raw", { value: raw });
268 }
269 else {
270 cooked.raw = raw;
271 }
272 return cooked;
273 }
274 ;
275 var __setModuleDefault = Object.create ? (function (o, v) {
276 Object.defineProperty(o, "default", { enumerable: true, value: v });
277 }) : function (o, v) {
278 o["default"] = v;
279 };
280 function __importStar(mod) {
281 if (mod && mod.__esModule)
282 return mod;
283 var result = {};
284 if (mod != null)
285 for (var k in mod)
286 if (Object.hasOwnProperty.call(mod, k))
287 __createBinding(result, mod, k);
288 __setModuleDefault(result, mod);
289 return result;
290 }
291 function __importDefault(mod) {
292 return (mod && mod.__esModule) ? mod : { default: mod };
293 }
294 function __classPrivateFieldGet(receiver, privateMap) {
295 if (!privateMap.has(receiver)) {
296 throw new TypeError("attempted to get private field on non-instance");
297 }
298 return privateMap.get(receiver);
299 }
300 function __classPrivateFieldSet(receiver, privateMap, value) {
301 if (!privateMap.has(receiver)) {
302 throw new TypeError("attempted to set private field on non-instance");
303 }
304 privateMap.set(receiver, value);
305 return value;
306 }
307
308 var fetch = function (req, httpClient, extractFiles) {
309 var shouldUseBody = ['POST', 'PUT', 'PATCH'].indexOf(req.method.toUpperCase()) !== -1;
310 var shouldStringify = function (param) { return ['variables', 'extensions'].indexOf(param.toLowerCase()) !== -1; };
311 var isBatching = req.body.length;
312 var shouldUseMultipart = req.options && req.options.useMultipart;
313 var multipartInfo;
314 if (shouldUseMultipart) {
315 if (isBatching) {
316 return new rxjs.Observable(function (observer) { return observer.error(new Error('File upload is not available when combined with Batching')); });
317 }
318 if (!shouldUseBody) {
319 return new rxjs.Observable(function (observer) { return observer.error(new Error('File upload is not available when GET is used')); });
320 }
321 multipartInfo = extractFiles(req.body);
322 shouldUseMultipart = !!multipartInfo.files.size;
323 }
324 // `body` for some, `params` for others
325 var bodyOrParams = {};
326 if (isBatching) {
327 if (!shouldUseBody) {
328 return new rxjs.Observable(function (observer) { return observer.error(new Error('Batching is not available for GET requests')); });
329 }
330 bodyOrParams = {
331 body: req.body,
332 };
333 }
334 else {
335 var body = shouldUseMultipart ? multipartInfo.clone : req.body;
336 if (shouldUseBody) {
337 bodyOrParams = {
338 body: body,
339 };
340 }
341 else {
342 var params = Object.keys(req.body).reduce(function (obj, param) {
343 var value = req.body[param];
344 obj[param] = shouldStringify(param) ? JSON.stringify(value) : value;
345 return obj;
346 }, {});
347 bodyOrParams = { params: params };
348 }
349 }
350 if (shouldUseMultipart && shouldUseBody) {
351 var form_1 = new FormData();
352 form_1.append('operations', JSON.stringify(bodyOrParams.body));
353 var map_1 = {};
354 var files = multipartInfo.files;
355 var i_1 = 0;
356 files.forEach(function (paths) {
357 map_1[++i_1] = paths;
358 });
359 form_1.append('map', JSON.stringify(map_1));
360 i_1 = 0;
361 files.forEach(function (_, file) {
362 form_1.append(++i_1 + '', file, file.name);
363 });
364 bodyOrParams.body = form_1;
365 }
366 // create a request
367 return httpClient.request(req.method, req.url, Object.assign(Object.assign({ observe: 'response', responseType: 'json', reportProgress: false }, bodyOrParams), req.options));
368 };
369 var mergeHeaders = function (source, destination) {
370 if (source && destination) {
371 var merged = destination
372 .keys()
373 .reduce(function (headers, name) { return headers.set(name, destination.getAll(name)); }, source);
374 return merged;
375 }
376 return destination || source;
377 };
378 function prioritize() {
379 var values = [];
380 for (var _i = 0; _i < arguments.length; _i++) {
381 values[_i] = arguments[_i];
382 }
383 var picked = values.find(function (val) { return typeof val !== 'undefined'; });
384 if (typeof picked === 'undefined') {
385 return values[values.length - 1];
386 }
387 return picked;
388 }
389
390 // XXX find a better name for it
391 var HttpLinkHandler = /** @class */ (function (_super) {
392 __extends(HttpLinkHandler, _super);
393 function HttpLinkHandler(httpClient, options) {
394 var _this = _super.call(this) || this;
395 _this.httpClient = httpClient;
396 _this.options = options;
397 _this.requester = function (operation) { return new core.Observable(function (observer) {
398 var context = operation.getContext();
399 // decides which value to pick, Context, Options or to just use the default
400 var pick = function (key, init) {
401 return prioritize(context[key], _this.options[key], init);
402 };
403 var includeQuery = pick('includeQuery', true);
404 var includeExtensions = pick('includeExtensions', false);
405 var method = pick('method', 'POST');
406 var url = pick('uri', 'graphql');
407 var withCredentials = pick('withCredentials');
408 var useMultipart = pick('useMultipart');
409 var req = {
410 method: method,
411 url: typeof url === 'function' ? url(operation) : url,
412 body: {
413 operationName: operation.operationName,
414 variables: operation.variables,
415 },
416 options: {
417 withCredentials: withCredentials,
418 useMultipart: useMultipart,
419 headers: _this.options.headers,
420 },
421 };
422 if (includeExtensions) {
423 req.body.extensions = operation.extensions;
424 }
425 if (includeQuery) {
426 req.body.query = graphql.print(operation.query);
427 }
428 if (context.headers) {
429 req.options.headers = mergeHeaders(req.options.headers, context.headers);
430 }
431 var sub = fetch(req, _this.httpClient, extractFiles.extractFiles).subscribe({
432 next: function (response) {
433 operation.setContext({ response: response });
434 observer.next(response.body);
435 },
436 error: function (err) { return observer.error(err); },
437 complete: function () { return observer.complete(); },
438 });
439 return function () {
440 if (!sub.closed) {
441 sub.unsubscribe();
442 }
443 };
444 }); };
445 return _this;
446 }
447 HttpLinkHandler.prototype.request = function (op) {
448 return this.requester(op);
449 };
450 return HttpLinkHandler;
451 }(core.ApolloLink));
452 var HttpLink = /** @class */ (function () {
453 function HttpLink(httpClient) {
454 this.httpClient = httpClient;
455 }
456 HttpLink.prototype.create = function (options) {
457 return new HttpLinkHandler(this.httpClient, options);
458 };
459 return HttpLink;
460 }());
461 HttpLink.ɵprov = i0.ɵɵdefineInjectable({ factory: function HttpLink_Factory() { return new HttpLink(i0.ɵɵinject(i1.HttpClient)); }, token: HttpLink, providedIn: "root" });
462 HttpLink.decorators = [
463 { type: i0.Injectable, args: [{
464 providedIn: 'root',
465 },] }
466 ];
467 HttpLink.ctorParameters = function () { return [
468 { type: i1.HttpClient }
469 ]; };
470
471 var defaults = {
472 batchInterval: 10,
473 batchMax: 10,
474 uri: 'graphql',
475 method: 'POST',
476 };
477 var HttpBatchLinkHandler = /** @class */ (function (_super) {
478 __extends(HttpBatchLinkHandler, _super);
479 function HttpBatchLinkHandler(httpClient, options) {
480 var _this = _super.call(this) || this;
481 _this.httpClient = httpClient;
482 _this.options = options;
483 _this.batchInterval = options.batchInterval || defaults.batchInterval;
484 _this.batchMax = options.batchMax || defaults.batchMax;
485 var batchHandler = function (operations) {
486 return new core.Observable(function (observer) {
487 var body = _this.createBody(operations);
488 var headers = _this.createHeaders(operations);
489 var _a = _this.createOptions(operations), method = _a.method, uri = _a.uri, withCredentials = _a.withCredentials;
490 if (typeof uri === 'function') {
491 throw new Error("Option 'uri' is a function, should be a string");
492 }
493 var req = {
494 method: method,
495 url: uri,
496 body: body,
497 options: {
498 withCredentials: withCredentials,
499 headers: headers,
500 },
501 };
502 var sub = fetch(req, _this.httpClient, function () {
503 throw new Error('File upload is not available when combined with Batching');
504 }).subscribe({
505 next: function (result) { return observer.next(result.body); },
506 error: function (err) { return observer.error(err); },
507 complete: function () { return observer.complete(); },
508 });
509 return function () {
510 if (!sub.closed) {
511 sub.unsubscribe();
512 }
513 };
514 });
515 };
516 var batchKey = options.batchKey ||
517 (function (operation) {
518 return _this.createBatchKey(operation);
519 });
520 _this.batcher = new batch.BatchLink({
521 batchInterval: _this.batchInterval,
522 batchMax: _this.batchMax,
523 batchKey: batchKey,
524 batchHandler: batchHandler,
525 });
526 return _this;
527 }
528 HttpBatchLinkHandler.prototype.createOptions = function (operations) {
529 var context = operations[0].getContext();
530 return {
531 method: prioritize(context.method, this.options.method, defaults.method),
532 uri: prioritize(context.uri, this.options.uri, defaults.uri),
533 withCredentials: prioritize(context.withCredentials, this.options.withCredentials),
534 };
535 };
536 HttpBatchLinkHandler.prototype.createBody = function (operations) {
537 var _this = this;
538 return operations.map(function (operation) {
539 var includeExtensions = prioritize(operation.getContext().includeExtensions, _this.options.includeExtensions, false);
540 var includeQuery = prioritize(operation.getContext().includeQuery, _this.options.includeQuery, true);
541 var body = {
542 operationName: operation.operationName,
543 variables: operation.variables,
544 };
545 if (includeExtensions) {
546 body.extensions = operation.extensions;
547 }
548 if (includeQuery) {
549 body.query = graphql.print(operation.query);
550 }
551 return body;
552 });
553 };
554 HttpBatchLinkHandler.prototype.createHeaders = function (operations) {
555 return operations.reduce(function (headers, operation) {
556 return mergeHeaders(headers, operation.getContext().headers);
557 }, this.options.headers);
558 };
559 HttpBatchLinkHandler.prototype.createBatchKey = function (operation) {
560 var context = operation.getContext();
561 if (context.skipBatching) {
562 return Math.random().toString(36).substr(2, 9);
563 }
564 var headers = context.headers &&
565 context.headers.keys().map(function (k) { return context.headers.get(k); });
566 var opts = JSON.stringify({
567 includeQuery: context.includeQuery,
568 includeExtensions: context.includeExtensions,
569 headers: headers,
570 });
571 return prioritize(context.uri, this.options.uri) + opts;
572 };
573 HttpBatchLinkHandler.prototype.request = function (op) {
574 return this.batcher.request(op);
575 };
576 return HttpBatchLinkHandler;
577 }(core.ApolloLink));
578 var HttpBatchLink = /** @class */ (function () {
579 function HttpBatchLink(httpClient) {
580 this.httpClient = httpClient;
581 }
582 HttpBatchLink.prototype.create = function (options) {
583 return new HttpBatchLinkHandler(this.httpClient, options);
584 };
585 return HttpBatchLink;
586 }());
587 HttpBatchLink.ɵprov = i0.ɵɵdefineInjectable({ factory: function HttpBatchLink_Factory() { return new HttpBatchLink(i0.ɵɵinject(i1.HttpClient)); }, token: HttpBatchLink, providedIn: "root" });
588 HttpBatchLink.decorators = [
589 { type: i0.Injectable, args: [{
590 providedIn: 'root',
591 },] }
592 ];
593 HttpBatchLink.ctorParameters = function () { return [
594 { type: i1.HttpClient }
595 ]; };
596
597 // http
598
599 /**
600 * Generated bundle index. Do not edit.
601 */
602
603 exports.HttpBatchLink = HttpBatchLink;
604 exports.HttpBatchLinkHandler = HttpBatchLinkHandler;
605 exports.HttpLink = HttpLink;
606 exports.HttpLinkHandler = HttpLinkHandler;
607
608 Object.defineProperty(exports, '__esModule', { value: true });
609
610})));
611//# sourceMappingURL=ngApolloLinkHttp.umd.js.map