All files / lib/src Query.js

91.92% Statements 182/198
81.67% Branches 98/120
86.67% Functions 26/30
92.77% Lines 154/166

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 26827x 27x     27x 27x 27x 27x     27x               27x 29x 158x 72x 29x 29x   29x           27x 27x   225x 1800x 811x   1800x       537x                 537x   27x 27x   187x 187x 187x 187x 162x 16x 146x 146x   182x 182x 12x 12x   170x 170x     13x 13x   13x       187x 77x 74x 74x     187x 183x 183x 4x 4x 4x 1x   3x 1x     183x 183x   187x 537x 537x 537x 537x 537x 537x 2x   537x 537x 286x   251x 28x         223x 223x   537x 334x 334x 2x 1x     1x 1x         537x 537x   187x 187x 187x 183x   27x 30x 1x 29x 29x 29x 2x 27x 2x   27x 27x 27x   27x 130x 130x 9x 121x 121x 1x 1x         27x 36x 4x 4x   32x 32x       32x 6x       6x   6x 6x 6x 6x   32x 3x   32x 30x 2x 28x   27x 51x 51x   27x 391x 391x 391x   27x 231x 231x 231x 225x                     27x 193x 189x 186x         189x   27x 38x 6x 38x     27x 13x 13x 13x 13x 13x 13x   27x       27x                     27x      
var __extends = (this && this.__extends) || (function () {
    var extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __assign = (this && this.__assign) || Object.assign || function(t) {
    for (var s, i = 1, n = arguments.length; i < n; i++) {
        s = arguments[i];
        for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
            t[p] = s[p];
    }
    return t;
};
var __rest = (this && this.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    Eif (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)
            t[p[i]] = s[p[i]];
    return t;
};
import * as React from 'react';
import * as PropTypes from 'prop-types';
import { ApolloError, } from 'apollo-client';
import { parser, DocumentType } from './parser';
var shallowEqual = require('fbjs/lib/shallowEqual');
var invariant = require('invariant');
function compact(obj) {
    return Object.keys(obj).reduce(function (acc, key) {
        if (obj[key] !== undefined) {
            acc[key] = obj[key];
        }
        return acc;
    }, {});
}
function observableQueryFields(observable) {
    var fields = {
        variables: observable.variables,
        refetch: observable.refetch.bind(observable),
        fetchMore: observable.fetchMore.bind(observable),
        updateQuery: observable.updateQuery.bind(observable),
        startPolling: observable.startPolling.bind(observable),
        stopPolling: observable.stopPolling.bind(observable),
        subscribeToMore: observable.subscribeToMore.bind(observable),
    };
    return fields;
}
var Query = (function (_super) {
    __extends(Query, _super);
    function Query(props, context) {
        var _this = _super.call(this, props, context) || this;
        _this.previousData = {};
        _this.hasMounted = false;
        _this.startQuerySubscription = function () {
            if (_this.querySubscription)
                return;
            var initial = _this.getQueryResult();
            _this.querySubscription = _this.queryObservable.subscribe({
                next: function (_a) {
                    var data = _a.data;
                    if (initial && initial.networkStatus === 7 && shallowEqual(initial.data, data)) {
                        initial = undefined;
                        return;
                    }
                    initial = undefined;
                    _this.updateCurrentData();
                },
                error: function (error) {
                    _this.resubscribeToQuery();
                    Iif (!error.hasOwnProperty('graphQLErrors'))
                        throw error;
                    _this.updateCurrentData();
                },
            });
        };
        _this.removeQuerySubscription = function () {
            if (_this.querySubscription) {
                _this.querySubscription.unsubscribe();
                delete _this.querySubscription;
            }
        };
        _this.updateCurrentData = function () {
            var _a = _this.props, onCompleted = _a.onCompleted, onError = _a.onError;
            if (onCompleted || onError) {
                var currentResult = _this.queryObservable.currentResult();
                var loading = currentResult.loading, error = currentResult.error, data = currentResult.data;
                if (onCompleted && !loading && !error) {
                    onCompleted(data);
                }
                else if (onError && !loading && error) {
                    onError(error);
                }
            }
            Eif (_this.hasMounted)
                _this.forceUpdate();
        };
        _this.getQueryResult = function () {
            var data = { data: Object.create(null) };
            Object.assign(data, observableQueryFields(_this.queryObservable));
            var currentResult = _this.queryObservable.currentResult();
            var loading = currentResult.loading, networkStatus = currentResult.networkStatus, errors = currentResult.errors, loadingState = currentResult.loadingState;
            var error = currentResult.error;
            if (errors && errors.length > 0) {
                error = new ApolloError({ graphQLErrors: errors });
            }
            Object.assign(data, { loading: loading, networkStatus: networkStatus, error: error, loadingState: loadingState });
            if (loading) {
                Object.assign(data.data, _this.previousData, currentResult.data);
            }
            else if (error) {
                Object.assign(data, {
                    data: (_this.queryObservable.getLastResult() || {}).data,
                });
            }
            else {
                Object.assign(data.data, currentResult.data);
                _this.previousData = currentResult.data;
            }
            if (!_this.querySubscription) {
                var oldRefetch_1 = data.refetch;
                data.refetch = function (args) {
                    if (_this.querySubscription) {
                        return oldRefetch_1(args);
                    }
                    else {
                        return new Promise(function (r, f) {
                            _this.refetcherQueue = { resolve: r, reject: f, args: args };
                        });
                    }
                };
            }
            data.client = _this.client;
            return data;
        };
        _this.client = props.client || context.client;
        invariant(!!_this.client, "Could not find \"client\" in the context of Query or as passed props. Wrap the root component in an <ApolloProvider>");
        _this.initializeQueryObservable(props);
        return _this;
    }
    Query.prototype.fetchData = function () {
        if (this.props.skip)
            return false;
        var _a = this.props, children = _a.children, ssr = _a.ssr, displayName = _a.displayName, skip = _a.skip, client = _a.client, onCompleted = _a.onCompleted, onError = _a.onError, opts = __rest(_a, ["children", "ssr", "displayName", "skip", "client", "onCompleted", "onError"]);
        var fetchPolicy = opts.fetchPolicy;
        if (ssr === false)
            return false;
        if (fetchPolicy === 'network-only' || fetchPolicy === 'cache-and-network') {
            fetchPolicy = 'cache-first';
        }
        var observable = this.client.watchQuery(__assign({}, opts, { fetchPolicy: fetchPolicy }));
        var result = this.queryObservable.currentResult();
        return result.loading ? observable.result() : false;
    };
    Query.prototype.componentDidMount = function () {
        this.hasMounted = true;
        if (this.props.skip)
            return;
        this.startQuerySubscription();
        if (this.refetcherQueue) {
            var _a = this.refetcherQueue, args = _a.args, resolve = _a.resolve, reject = _a.reject;
            this.queryObservable.refetch(args)
                .then(resolve)
                .catch(reject);
        }
    };
    Query.prototype.componentWillReceiveProps = function (nextProps, nextContext) {
        if (nextProps.skip && !this.props.skip) {
            this.removeQuerySubscription();
            return;
        }
        var client = nextProps.client;
        Iif (shallowEqual(this.props, nextProps) &&
            (this.client === client || this.client === nextContext.client)) {
            return;
        }
        if (this.client !== client && this.client !== nextContext.client) {
            Iif (client) {
                this.client = client;
            }
            else {
                this.client = nextContext.client;
            }
            this.removeQuerySubscription();
            this.queryObservable = null;
            this.previousData = {};
            this.updateQuery(nextProps);
        }
        if (this.props.query !== nextProps.query) {
            this.removeQuerySubscription();
        }
        this.updateQuery(nextProps);
        if (nextProps.skip)
            return;
        this.startQuerySubscription();
    };
    Query.prototype.componentWillUnmount = function () {
        this.removeQuerySubscription();
        this.hasMounted = false;
    };
    Query.prototype.render = function () {
        var children = this.props.children;
        var queryResult = this.getQueryResult();
        return children(queryResult);
    };
    Query.prototype.extractOptsFromProps = function (props) {
        var variables = props.variables, pollInterval = props.pollInterval, fetchPolicy = props.fetchPolicy, errorPolicy = props.errorPolicy, notifyOnNetworkStatusChange = props.notifyOnNetworkStatusChange, query = props.query, _a = props.displayName, displayName = _a === void 0 ? 'Query' : _a, _b = props.context, context = _b === void 0 ? {} : _b;
        this.operation = parser(query);
        invariant(this.operation.type === DocumentType.Query, "The <Query /> component requires a graphql query, but got a " + (this.operation.type === DocumentType.Mutation ? 'mutation' : 'subscription') + ".");
        return compact({
            variables: variables,
            pollInterval: pollInterval,
            query: query,
            fetchPolicy: fetchPolicy,
            errorPolicy: errorPolicy,
            notifyOnNetworkStatusChange: notifyOnNetworkStatusChange,
            metadata: { reactComponent: { displayName: displayName } },
            context: context,
        });
    };
    Query.prototype.initializeQueryObservable = function (props) {
        var opts = this.extractOptsFromProps(props);
        if (this.context.operations) {
            this.context.operations.set(this.operation.name, {
                query: opts.query,
                variables: opts.variables,
            });
        }
        this.queryObservable = this.client.watchQuery(opts);
    };
    Query.prototype.updateQuery = function (props) {
        if (!this.queryObservable)
            this.initializeQueryObservable(props);
        this.queryObservable.setOptions(this.extractOptsFromProps(props))
            .catch(function () { return null; });
    };
    Query.prototype.resubscribeToQuery = function () {
        this.removeQuerySubscription();
        var lastError = this.queryObservable.getLastError();
        var lastResult = this.queryObservable.getLastResult();
        this.queryObservable.resetLastResults();
        this.startQuerySubscription();
        Object.assign(this.queryObservable, { lastError: lastError, lastResult: lastResult });
    };
    Query.contextTypes = {
        client: PropTypes.object.isRequired,
        operations: PropTypes.object,
    };
    Query.propTypes = {
        children: PropTypes.func.isRequired,
        fetchPolicy: PropTypes.string,
        notifyOnNetworkStatusChange: PropTypes.bool,
        onCompleted: PropTypes.func,
        onError: PropTypes.func,
        pollInterval: PropTypes.number,
        query: PropTypes.object.isRequired,
        variables: PropTypes.object,
        ssr: PropTypes.bool,
    };
    return Query;
}(React.Component));
export default Query;
//# sourceMappingURL=Query.js.map