UNPKG

11.9 kBSource Map (JSON)View Raw
1{"version":3,"file":"bundle.umd.js","sources":["../src/httpLink.ts"],"sourcesContent":["import { ApolloLink, Observable, RequestHandler, fromError } from 'apollo-link';\nimport {\n serializeFetchParameter,\n selectURI,\n parseAndCheckHttpResponse,\n checkFetcher,\n selectHttpOptionsAndBody,\n createSignalIfSupported,\n fallbackHttpConfig,\n Body,\n HttpOptions,\n UriFunction as _UriFunction,\n} from 'apollo-link-http-common';\nimport { DefinitionNode } from 'graphql';\n\nexport namespace HttpLink {\n //TODO Would much rather be able to export directly\n export interface UriFunction extends _UriFunction {}\n export interface Options extends HttpOptions {\n /**\n * If set to true, use the HTTP GET method for query operations. Mutations\n * will still use the method specified in fetchOptions.method (which defaults\n * to POST).\n */\n useGETForQueries?: boolean;\n }\n}\n\n// For backwards compatibility.\nexport import FetchOptions = HttpLink.Options;\nexport import UriFunction = HttpLink.UriFunction;\n\nexport const createHttpLink = (linkOptions: HttpLink.Options = {}) => {\n let {\n uri = '/graphql',\n // use default global fetch is nothing passed in\n fetch: fetcher,\n includeExtensions,\n useGETForQueries,\n ...requestOptions\n } = linkOptions;\n\n // dev warnings to ensure fetch is present\n checkFetcher(fetcher);\n\n //fetcher is set here rather than the destructuring to ensure fetch is\n //declared before referencing it. Reference in the destructuring would cause\n //a ReferenceError\n if (!fetcher) {\n fetcher = fetch;\n }\n\n const linkConfig = {\n http: { includeExtensions },\n options: requestOptions.fetchOptions,\n credentials: requestOptions.credentials,\n headers: requestOptions.headers,\n };\n\n return new ApolloLink(operation => {\n let chosenURI = selectURI(operation, uri);\n\n const context = operation.getContext();\n\n const contextConfig = {\n http: context.http,\n options: context.fetchOptions,\n credentials: context.credentials,\n headers: context.headers,\n };\n\n //uses fallback, link, and then context to build options\n const { options, body } = selectHttpOptionsAndBody(\n operation,\n fallbackHttpConfig,\n linkConfig,\n contextConfig,\n );\n\n const { controller, signal } = createSignalIfSupported();\n if (controller) (options as any).signal = signal;\n\n // If requested, set method to GET if there are no mutations.\n const definitionIsMutation = (d: DefinitionNode) => {\n return d.kind === 'OperationDefinition' && d.operation === 'mutation';\n };\n if (\n useGETForQueries &&\n !operation.query.definitions.some(definitionIsMutation)\n ) {\n options.method = 'GET';\n }\n\n if (options.method === 'GET') {\n const { newURI, parseError } = rewriteURIForGET(chosenURI, body);\n if (parseError) {\n return fromError(parseError);\n }\n chosenURI = newURI;\n } else {\n try {\n (options as any).body = serializeFetchParameter(body, 'Payload');\n } catch (parseError) {\n return fromError(parseError);\n }\n }\n\n return new Observable(observer => {\n fetcher(chosenURI, options)\n .then(response => {\n operation.setContext({ response });\n return response;\n })\n .then(parseAndCheckHttpResponse(operation))\n .then(result => {\n // we have data and can send it to back up the link chain\n observer.next(result);\n observer.complete();\n return result;\n })\n .catch(err => {\n // fetch was cancelled so its already been cleaned up in the unsubscribe\n if (err.name === 'AbortError') return;\n // if it is a network error, BUT there is graphql result info\n // fire the next observer before calling error\n // this gives apollo-client (and react-apollo) the `graphqlErrors` and `networErrors`\n // to pass to UI\n // this should only happen if we *also* have data as part of the response key per\n // the spec\n if (err.result && err.result.errors && err.result.data) {\n // if we dont' call next, the UI can only show networkError because AC didn't\n // get andy graphqlErrors\n // this is graphql execution result info (i.e errors and possibly data)\n // this is because there is no formal spec how errors should translate to\n // http status codes. So an auth error (401) could have both data\n // from a public field, errors from a private field, and a status of 401\n // {\n // user { // this will have errors\n // firstName\n // }\n // products { // this is public so will have data\n // cost\n // }\n // }\n //\n // the result of above *could* look like this:\n // {\n // data: { products: [{ cost: \"$10\" }] },\n // errors: [{\n // message: 'your session has timed out',\n // path: []\n // }]\n // }\n // status code of above would be a 401\n // in the UI you want to show data where you can, errors as data where you can\n // and use correct http status codes\n observer.next(err.result);\n }\n observer.error(err);\n });\n\n return () => {\n // XXX support canceling this request\n // https://developers.google.com/web/updates/2017/09/abortable-fetch\n if (controller) controller.abort();\n };\n });\n });\n};\n\n// For GET operations, returns the given URI rewritten with parameters, or a\n// parse error.\nfunction rewriteURIForGET(chosenURI: string, body: Body) {\n // Implement the standard HTTP GET serialization, plus 'extensions'. Note\n // the extra level of JSON serialization!\n const queryParams = [];\n const addQueryParam = (key: string, value: string) => {\n queryParams.push(`${key}=${encodeURIComponent(value)}`);\n };\n\n if ('query' in body) {\n addQueryParam('query', body.query);\n }\n if (body.operationName) {\n addQueryParam('operationName', body.operationName);\n }\n if (body.variables) {\n let serializedVariables;\n try {\n serializedVariables = serializeFetchParameter(\n body.variables,\n 'Variables map',\n );\n } catch (parseError) {\n return { parseError };\n }\n addQueryParam('variables', serializedVariables);\n }\n if (body.extensions) {\n let serializedExtensions;\n try {\n serializedExtensions = serializeFetchParameter(\n body.extensions,\n 'Extensions map',\n );\n } catch (parseError) {\n return { parseError };\n }\n addQueryParam('extensions', serializedExtensions);\n }\n\n // Reconstruct the URI with added query params.\n // XXX This assumes that the URI is well-formed and that it doesn't\n // already contain any of these query params. We could instead use the\n // URL API and take a polyfill (whatwg-url@6) for older browsers that\n // don't support URLSearchParams. Note that some browsers (and\n // versions of whatwg-url) support URL but not URLSearchParams!\n let fragment = '',\n preFragment = chosenURI;\n const fragmentStart = chosenURI.indexOf('#');\n if (fragmentStart !== -1) {\n fragment = chosenURI.substr(fragmentStart);\n preFragment = chosenURI.substr(0, fragmentStart);\n }\n const queryParamsPrefix = preFragment.indexOf('?') === -1 ? '?' : '&';\n const newURI =\n preFragment + queryParamsPrefix + queryParams.join('&') + fragment;\n return { newURI };\n}\n\nexport class HttpLink extends ApolloLink {\n public requester: RequestHandler;\n constructor(opts?: HttpLink.Options) {\n super(createHttpLink(opts).request);\n }\n}\n"],"names":["checkFetcher","ApolloLink","selectURI","fromError","serializeFetchParameter","Observable","parseAndCheckHttpResponse"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAAA,IAgCa,cAAc,GAAG,UAAC,WAAkC;IAAlC,4BAAA,EAAA,gBAAkC;IAE7D,IAAA,oBAAgB,EAAhB,qCAAgB,EAEhB,2BAAc,EACd,iDAAiB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