UNPKG

1.86 kBTypeScriptView Raw
1import ApolloClient, { ApolloQueryResult, QueryOptions } from 'apollo-client';
2import { DocumentNode } from 'graphql';
3import hoistNonReactStatics from 'hoist-non-react-statics';
4import * as PropTypes from 'prop-types';
5import * as React from "react";
6import { getClient } from "react-apollo/component-utils";
7
8export function withLazyQuery<TProps extends TGraphQLVariables | {} = {},
9 TData = {},
10 TGraphQLVariables = {},
11 TChildProps extends {
12 fetch: (options?: QueryOptions<TGraphQLVariables>) => Promise<ApolloQueryResult<TData>>;
13 } | {} = {}>(
14 document: DocumentNode,
15 operationOptions: { name?: string; options?: QueryOptions<TGraphQLVariables> } = {} = {},
16) {
17 return (
18 WrappedComponent: React.ComponentType<TProps & TChildProps>,
19 ): React.ComponentType<TProps> => {
20 class GraphQL extends React.Component<TProps> {
21 static WrappedComponent = WrappedComponent;
22
23 static contextTypes = {
24 client: PropTypes.object,
25 };
26
27 private client: ApolloClient<any>;
28
29 constructor(props, context) {
30 super(props, context);
31
32 this.client = getClient(props, context);
33 }
34
35 fetch = (options?: QueryOptions<TGraphQLVariables>): Promise<ApolloQueryResult<TData>> => {
36 const queryOptions = operationOptions.options || {};
37 return (this.client as ApolloClient<any>).query({
38 query: document,
39 ...queryOptions,
40 ...options,
41 });
42 }
43
44 render() {
45 const { name = 'fetch' } = operationOptions;
46 return (
47 <WrappedComponent
48 {...this.props as TProps}
49 {...{ [name]: this.fetch } as TChildProps}
50 />
51 );
52 }
53 }
54
55 // Make sure we preserve any custom statics on the original component.
56 return hoistNonReactStatics<TProps, any>(GraphQL, WrappedComponent, {});
57 };
58}
\No newline at end of file