UNPKG

6.13 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3const apollo_cache_inmemory_1 = require("apollo-cache-inmemory");
4const apollo_client_1 = require("apollo-client");
5const apollo_link_1 = require("apollo-link");
6const apollo_link_error_1 = require("apollo-link-error");
7const apollo_link_http_1 = require("apollo-link-http");
8const axios_1 = require("axios");
9const axios_fetch_1 = require("axios-fetch");
10const graphql_tag_1 = require("graphql-tag");
11const stringify = require("json-stringify-safe");
12const trace = require("stack-trace");
13const internalGraphql = require("../internal/graph/graphQL");
14const namespace = require("../internal/util/cls");
15const http_1 = require("../internal/util/http");
16const string_1 = require("../internal/util/string");
17const logger_1 = require("../util/logger");
18graphql_tag_1.disableFragmentWarnings();
19/**
20 * Implementation of GraphClient using Apollo Client.
21 */
22class ApolloGraphClient {
23 /**
24 * Create a new GraphClient
25 * @param endpoint GraphQL endpoint
26 * @param headers any special headers to use
27 * @param fetch configured GlobalFetch instance to use for this GraphClient
28 */
29 constructor(endpoint, headers = {}, fetch = axios_fetch_1.buildAxiosFetch(axios_1.default.create(http_1.configureProxy({}))), listeners = []) {
30 this.endpoint = endpoint;
31 this.headers = headers;
32 this.fetch = fetch;
33 this.listeners = listeners;
34 const cache = new apollo_cache_inmemory_1.InMemoryCache({
35 addTypename: false,
36 });
37 const httpLink = apollo_link_http_1.createHttpLink({
38 uri: endpoint,
39 fetch,
40 });
41 const middlewareLink = new apollo_link_1.ApolloLink((operation, forward) => {
42 // attach the correlation-id to the request
43 const correlationId = namespace.get() ? namespace.get().correlationId : undefined;
44 if (!!correlationId) {
45 headers["correlation-id"] = correlationId;
46 }
47 const invocationId = namespace.get() ? namespace.get().invocationId : string_1.guid();
48 if (!!invocationId) {
49 headers["x-request-id"] = invocationId;
50 }
51 operation.setContext({
52 headers,
53 });
54 for (const listener of this.listeners) {
55 operation = listener.operationStarting(operation);
56 }
57 return forward(operation);
58 });
59 const errorLink = apollo_link_error_1.onError(({ graphQLErrors, networkError, response }) => {
60 let msg = `GraphQL operation failed:`;
61 if (!!graphQLErrors) {
62 const g = graphQLErrors.map(({ message }) => ` [GraphQL]: ${message}`);
63 msg += `${g.join(" ")}`;
64 }
65 if (!!networkError) {
66 msg += ` [Network]: ${networkError}`;
67 }
68 if (!!response) {
69 msg += ` [Response]: ${stringify(response, string_1.replacer)}`;
70 }
71 logger_1.logger.error(msg);
72 });
73 const link = errorLink.concat(middlewareLink.concat(httpLink));
74 this.client = new apollo_client_1.default({
75 link,
76 cache,
77 });
78 }
79 query(options) {
80 if (typeof options === "string") {
81 options = {
82 name: options,
83 };
84 }
85 const q = internalGraphql.query({
86 query: options.query,
87 path: options.path,
88 name: options.name,
89 moduleDir: options.moduleDir ? options.moduleDir : trace.get()[1].getFileName(),
90 });
91 return this.executeQuery(q, options.variables, options.options);
92 }
93 mutate(options) {
94 if (typeof options === "string") {
95 options = {
96 name: options,
97 };
98 }
99 const m = internalGraphql.mutate({
100 mutation: options.mutation,
101 path: options.path,
102 name: options.name,
103 moduleDir: options.moduleDir ? options.moduleDir : trace.get()[1].getFileName(),
104 });
105 return this.executeMutation(m, options.variables, options.options);
106 }
107 executeQuery(q, variables, queryOptions) {
108 const log = !queryOptions ||
109 (queryOptions && queryOptions.log === undefined) ||
110 (queryOptions && queryOptions.log === true);
111 if (log) {
112 logger_1.logger.debug(`Querying '%s' with variables '%s' and query: %s`, this.endpoint, stringify(variables || {}), internalGraphql.inlineQuery(q));
113 }
114 const query = graphql_tag_1.default(q);
115 return this.client.query(Object.assign({ query,
116 variables, errorPolicy: "all" }, queryOptions))
117 .then(result => {
118 if (log) {
119 // The following statement is needed for debugging; we can always disable that later
120 logger_1.logger.debug("Query returned data: %s", stringify(result.data, string_1.replacer));
121 }
122 return result.data;
123 });
124 }
125 executeMutation(m, variables, mutationOptions) {
126 const log = !mutationOptions ||
127 (mutationOptions && mutationOptions.log === undefined) ||
128 (mutationOptions && mutationOptions.log === true);
129 if (log) {
130 logger_1.logger.debug(`Mutating '%s' with variables '%s' and mutation: %s`, this.endpoint, stringify(variables || {}), internalGraphql.inlineQuery(m));
131 }
132 const mutation = graphql_tag_1.default(m);
133 return this.client.mutate(Object.assign({ mutation,
134 variables, errorPolicy: "all" }, mutationOptions))
135 .then(response => {
136 if (log) {
137 // The following statement is needed for debugging; we can always disable that later
138 logger_1.logger.debug("Mutation returned data: %s", stringify(response.data, string_1.replacer));
139 }
140 return response.data;
141 });
142 }
143}
144exports.ApolloGraphClient = ApolloGraphClient;
145//# sourceMappingURL=ApolloGraphClient.js.map
\No newline at end of file