UNPKG

3.33 kBJavaScriptView Raw
1"use strict";
2var __importDefault = (this && this.__importDefault) || function (mod) {
3 return (mod && mod.__esModule) ? mod : { "default": mod };
4};
5Object.defineProperty(exports, "__esModule", { value: true });
6exports.GraphQLDataSource = void 0;
7const apollo_link_1 = require("apollo-link");
8const apollo_link_context_1 = require("apollo-link-context");
9const apollo_link_error_1 = require("apollo-link-error");
10const apollo_link_http_1 = require("apollo-link-http");
11const apollo_server_errors_1 = require("apollo-server-errors");
12const await_to_js_1 = __importDefault(require("await-to-js"));
13const apollo_env_1 = require("apollo-env");
14class GraphQLDataSource {
15 initialize(config) {
16 this.context = config.context;
17 }
18 async execute(operation) {
19 return this.executeSingleOperation(operation);
20 }
21 composeLinks() {
22 const uri = this.resolveUri();
23 return apollo_link_1.ApolloLink.from([
24 this.onErrorLink(),
25 this.onRequestLink(),
26 (0, apollo_link_http_1.createHttpLink)({ fetch: apollo_env_1.fetch, uri }),
27 ]);
28 }
29 didEncounterError(error) {
30 const status = error.statusCode ? error.statusCode : null;
31 const message = error.bodyText
32 ? error.bodyText
33 : error.message
34 ? error.message
35 : null;
36 let apolloError;
37 switch (status) {
38 case 401:
39 apolloError = new apollo_server_errors_1.AuthenticationError(message);
40 break;
41 case 403:
42 apolloError = new apollo_server_errors_1.ForbiddenError(message);
43 break;
44 default:
45 apolloError = new apollo_server_errors_1.ApolloError(message);
46 }
47 throw apolloError;
48 }
49 async executeSingleOperation(operation) {
50 const link = this.composeLinks();
51 const [error, response] = await (0, await_to_js_1.default)((0, apollo_link_1.makePromise)((0, apollo_link_1.execute)(link, operation)));
52 if (error) {
53 this.didEncounterError(error);
54 }
55 return response;
56 }
57 resolveUri() {
58 const baseURL = this.baseURL;
59 if (!baseURL) {
60 throw new apollo_server_errors_1.ApolloError("Cannot make request to GraphQL API, missing baseURL");
61 }
62 return baseURL;
63 }
64 onRequestLink() {
65 return (0, apollo_link_context_1.setContext)((_, request) => {
66 if (this.willSendRequest) {
67 this.willSendRequest(request);
68 }
69 return request;
70 });
71 }
72 onErrorLink() {
73 return (0, apollo_link_error_1.onError)(({ graphQLErrors, networkError, operation }) => {
74 const { result, response } = operation.getContext();
75 if (graphQLErrors) {
76 graphQLErrors.map((graphqlError) => console.error(`[GraphQL error]: ${graphqlError.message}`));
77 }
78 if (networkError) {
79 console.log(`[Network Error]: ${networkError}`);
80 }
81 if (response && response.status >= 400) {
82 console.log(`[Network Error] ${response.bodyText}`);
83 }
84 });
85 }
86}
87exports.GraphQLDataSource = GraphQLDataSource;
88//# sourceMappingURL=GraphQLDataSource.js.map
\No newline at end of file