1 | import { Injectable, NgModule } from '@angular/core';
|
2 | import { HttpClient } from '@angular/common/http';
|
3 | import { ApolloLink, Observable } from 'apollo-link';
|
4 | import { print } from 'graphql';
|
5 | import { prioritize, mergeHeaders, fetch } from 'apollo-angular-link-http-common';
|
6 | import { extractFiles } from 'extract-files';
|
7 |
|
8 |
|
9 | class HttpLinkHandler extends ApolloLink {
|
10 | constructor(httpClient, options) {
|
11 | super();
|
12 | this.httpClient = httpClient;
|
13 | this.options = options;
|
14 | this.requester = (operation) => new Observable((observer) => {
|
15 | const context = operation.getContext();
|
16 |
|
17 | const pick = (key, init) => {
|
18 | return prioritize(context[key], this.options[key], init);
|
19 | };
|
20 | const includeQuery = pick('includeQuery', true);
|
21 | const includeExtensions = pick('includeExtensions', false);
|
22 | const method = pick('method', 'POST');
|
23 | const url = pick('uri', 'graphql');
|
24 | const withCredentials = pick('withCredentials');
|
25 | const useMultipart = pick('useMultipart');
|
26 | const req = {
|
27 | method,
|
28 | url: typeof url === 'function' ? url(operation) : url,
|
29 | body: {
|
30 | operationName: operation.operationName,
|
31 | variables: operation.variables,
|
32 | },
|
33 | options: {
|
34 | withCredentials,
|
35 | useMultipart,
|
36 | headers: this.options.headers,
|
37 | },
|
38 | };
|
39 | if (includeExtensions) {
|
40 | req.body.extensions = operation.extensions;
|
41 | }
|
42 | if (includeQuery) {
|
43 | req.body.query = print(operation.query);
|
44 | }
|
45 | if (context.headers) {
|
46 | req.options.headers = mergeHeaders(req.options.headers, context.headers);
|
47 | }
|
48 | const sub = fetch(req, this.httpClient, extractFiles).subscribe({
|
49 | next: (response) => {
|
50 | operation.setContext({ response });
|
51 | observer.next(response.body);
|
52 | },
|
53 | error: (err) => observer.error(err),
|
54 | complete: () => observer.complete(),
|
55 | });
|
56 | return () => {
|
57 | if (!sub.closed) {
|
58 | sub.unsubscribe();
|
59 | }
|
60 | };
|
61 | });
|
62 | }
|
63 | request(op) {
|
64 | return this.requester(op);
|
65 | }
|
66 | }
|
67 | class HttpLink {
|
68 | constructor(httpClient) {
|
69 | this.httpClient = httpClient;
|
70 | }
|
71 | create(options) {
|
72 | return new HttpLinkHandler(this.httpClient, options);
|
73 | }
|
74 | }
|
75 | HttpLink.decorators = [
|
76 | { type: Injectable }
|
77 | ];
|
78 | HttpLink.ctorParameters = () => [
|
79 | { type: HttpClient }
|
80 | ];
|
81 |
|
82 | const PROVIDERS = [HttpLink];
|
83 | class HttpLinkModule {
|
84 | }
|
85 | HttpLinkModule.decorators = [
|
86 | { type: NgModule, args: [{
|
87 | providers: PROVIDERS,
|
88 | },] }
|
89 | ];
|
90 |
|
91 |
|
92 |
|
93 |
|
94 |
|
95 | export { HttpLink, HttpLinkHandler, HttpLinkModule, PROVIDERS };
|
96 |
|