apollo-angular-link-http
Version:
An Apollo Link to allow sending a single http request per operation.
98 lines (93 loc) • 3.29 kB
JavaScript
import { __decorate } from 'tslib';
import { Injectable, NgModule } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { ApolloLink, Observable } from 'apollo-link';
import { print } from 'graphql';
import { prioritize, mergeHeaders, fetch } from 'apollo-angular-link-http-common';
import { extractFiles } from 'extract-files';
// XXX find a better name for it
class HttpLinkHandler extends ApolloLink {
constructor(httpClient, options) {
super();
this.httpClient = httpClient;
this.options = options;
this.requester = (operation) => new Observable((observer) => {
const context = operation.getContext();
// decides which value to pick, Context, Options or to just use the default
const pick = (key, init) => {
return prioritize(context[key], this.options[key], init);
};
const includeQuery = pick('includeQuery', true);
const includeExtensions = pick('includeExtensions', false);
const method = pick('method', 'POST');
const url = pick('uri', 'graphql');
const withCredentials = pick('withCredentials');
const useMultipart = pick('useMultipart');
const req = {
method,
url: typeof url === 'function' ? url(operation) : url,
body: {
operationName: operation.operationName,
variables: operation.variables,
},
options: {
withCredentials,
useMultipart,
headers: this.options.headers,
},
};
if (includeExtensions) {
req.body.extensions = operation.extensions;
}
if (includeQuery) {
req.body.query = print(operation.query);
}
if (context.headers) {
req.options.headers = mergeHeaders(req.options.headers, context.headers);
}
const sub = fetch(req, this.httpClient, extractFiles).subscribe({
next: response => {
operation.setContext({ response });
observer.next(response.body);
},
error: err => observer.error(err),
complete: () => observer.complete(),
});
return () => {
if (!sub.closed) {
sub.unsubscribe();
}
};
});
}
request(op) {
return this.requester(op);
}
}
let HttpLink = class HttpLink {
constructor(httpClient) {
this.httpClient = httpClient;
}
create(options) {
return new HttpLinkHandler(this.httpClient, options);
}
};
HttpLink.ctorParameters = () => [
{ type: HttpClient }
];
HttpLink = __decorate([
Injectable()
], HttpLink);
const PROVIDERS = [HttpLink];
let HttpLinkModule = class HttpLinkModule {
};
HttpLinkModule = __decorate([
NgModule({
providers: PROVIDERS,
})
], HttpLinkModule);
/**
* Generated bundle index. Do not edit.
*/
export { HttpLink, HttpLinkHandler, HttpLinkModule, PROVIDERS };
//# sourceMappingURL=ngApolloLinkHttp.js.map