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
268
269
270
271
272
273
274
275
276
277 | 27x
27x
27x
27x
27x
27x
27x
27x
27x
46x
46x
46x
46x
44x
44x
27x
39x
27x
6x
27x
11x
11x
2x
9x
1x
1x
27x
93x
93x
93x
93x
63x
36x
36x
36x
30x
30x
6x
6x
46x
72x
36x
36x
4x
4x
3x
4x
36x
46x
36x
21x
46x
30x
1x
29x
29x
29x
29x
15x
14x
46x
6x
1x
5x
5x
5x
4x
1x
46x
36x
36x
46x
34x
46x
48x
48x
46x
46x
27x
27x
| import * as React from 'react';
import * as PropTypes from 'prop-types';
import ApolloClient, { PureQueryOptions, ApolloError } from 'apollo-client';
import { DataProxy } from 'apollo-cache';
const invariant = require('invariant');
import { DocumentNode, GraphQLError } from 'graphql';
const shallowEqual = require('fbjs/lib/shallowEqual');
import { OperationVariables, RefetchQueriesProviderFn } from './types';
import { parser, DocumentType } from './parser';
export interface MutationResult<TData = Record<string, any>> {
data?: TData;
error?: ApolloError;
loading: boolean;
called: boolean;
}
export interface MutationContext {
client: ApolloClient<Object>;
operations: Map<string, { query: DocumentNode; variables: any }>;
}
export interface ExecutionResult<T = Record<string, any>> {
data?: T;
extensions?: Record<string, any>;
errors?: GraphQLError[];
}
// Improved MutationUpdaterFn type, need to port them back to Apollo Client
export declare type MutationUpdaterFn<
T = {
[key: string]: any;
}
> = (proxy: DataProxy, mutationResult: FetchResult<T>) => void;
export declare type FetchResult<C = Record<string, any>, E = Record<string, any>> = ExecutionResult<
C
> & {
extensions?: E;
context?: C;
};
export declare type MutationOptions<TData = any, TVariables = OperationVariables> = {
variables?: TVariables;
optimisticResponse?: Object;
refetchQueries?: string[] | PureQueryOptions[] | RefetchQueriesProviderFn;
update?: MutationUpdaterFn<TData>;
};
export interface MutationProps<TData = any, TVariables = OperationVariables> {
mutation: DocumentNode;
ignoreResults?: boolean;
optimisticResponse?: Object;
variables?: TVariables;
refetchQueries?: string[] | PureQueryOptions[] | RefetchQueriesProviderFn;
update?: MutationUpdaterFn<TData>;
children: (
mutateFn: (options?: MutationOptions<TData, TVariables>) => Promise<void | FetchResult>,
result: MutationResult<TData>,
) => React.ReactNode;
onCompleted?: (data: TData) => void;
onError?: (error: ApolloError) => void;
context?: Record<string, any>;
}
export interface MutationState<TData = any> {
called: boolean;
error?: ApolloError;
data?: TData;
loading: boolean;
}
const initialState = {
loading: false,
called: false,
error: undefined,
data: undefined,
};
class Mutation<TData = any, TVariables = OperationVariables> extends React.Component<
MutationProps<TData, TVariables>,
MutationState<TData>
> {
static contextTypes = {
client: PropTypes.object.isRequired,
operations: PropTypes.object,
};
static propTypes = {
mutation: PropTypes.object.isRequired,
variables: PropTypes.object,
optimisticResponse: PropTypes.object,
refetchQueries: PropTypes.oneOfType([
PropTypes.arrayOf(PropTypes.string),
PropTypes.arrayOf(PropTypes.object),
PropTypes.func,
]),
update: PropTypes.func,
children: PropTypes.func.isRequired,
onCompleted: PropTypes.func,
onError: PropTypes.func,
};
private client: ApolloClient<any>;
private mostRecentMutationId: number;
private hasMounted: boolean;
constructor(props: MutationProps<TData, TVariables>, context: any) {
super(props, context);
this.verifyContext(context);
this.client = context.client;
this.verifyDocumentIsMutation(props.mutation);
this.mostRecentMutationId = 0;
this.state = initialState;
}
componentDidMount() {
this.hasMounted = true;
}
componentWillUnmount() {
this.hasMounted = false;
}
componentWillReceiveProps(
nextProps: MutationProps<TData, TVariables>,
nextContext: MutationContext,
) {
Iif (shallowEqual(this.props, nextProps) && this.client === nextContext.client) {
return;
}
if (this.props.mutation !== nextProps.mutation) {
this.verifyDocumentIsMutation(nextProps.mutation);
}
if (this.client !== nextContext.client) {
this.client = nextContext.client;
this.setState(initialState);
}
}
render() {
const { children } = this.props;
const { loading, data, error, called } = this.state;
const result = {
called,
loading,
data,
error,
};
return children(this.runMutation, result);
}
private runMutation = (options: MutationOptions<TVariables> = {}) => {
this.onStartMutation();
const mutationId = this.generateNewMutationId();
return this.mutate(options)
.then(response => {
this.onCompletedMutation(response, mutationId);
return response;
})
.catch(e => {
this.onMutationError(e, mutationId);
if (!this.props.onError) throw e;
});
};
private mutate = (options: MutationOptions<TVariables>) => {
const { mutation, variables, optimisticResponse, update, context = {} } = this.props;
let refetchQueries = options.refetchQueries || this.props.refetchQueries;
// XXX this will be removed in the 3.0 of Apollo Client. Currently, we
// support refectching of named queries which just pulls the latest
// variables to match. This forces us to either a) keep all queries around
// to be able to iterate over and refetch, or b) [new in 2.1] keep a map of
// operations on the client where operation name => { query, variables }
//
// Going forward, we should only allow using the full operation + variables to
// refetch.
if (refetchQueries && refetchQueries.length && Array.isArray(refetchQueries)) {
refetchQueries = (refetchQueries as any).map((x: string | PureQueryOptions) => {
if (typeof x === 'string' && this.context.operations) return this.context.operations.get(x) || x;
return x;
});
delete options.refetchQueries;
}
return this.client.mutate({
mutation,
variables,
optimisticResponse,
refetchQueries,
update,
context,
...options,
});
};
private onStartMutation = () => {
if (!this.state.loading && !this.props.ignoreResults) {
this.setState({
loading: true,
error: undefined,
data: undefined,
called: true,
});
}
};
private onCompletedMutation = (response: ExecutionResult<TData>, mutationId: number) => {
if (this.hasMounted === false) {
return;
}
const { onCompleted, ignoreResults } = this.props;
const data = response.data as TData;
const callOncomplete = () => (onCompleted ? onCompleted(data) : null);
if (this.isMostRecentMutation(mutationId) && !ignoreResults) {
this.setState({ loading: false, data }, callOncomplete);
} else {
callOncomplete();
}
};
private onMutationError = (error: ApolloError, mutationId: number) => {
if (this.hasMounted === false) {
return;
}
const { onError } = this.props;
const callOnError = () => (onError ? onError(error) : null);
if (this.isMostRecentMutation(mutationId)) {
this.setState({ loading: false, error }, callOnError);
} else {
callOnError();
}
};
private generateNewMutationId = (): number => {
this.mostRecentMutationId = this.mostRecentMutationId + 1;
return this.mostRecentMutationId;
};
private isMostRecentMutation = (mutationId: number) => {
return this.mostRecentMutationId === mutationId;
};
private verifyDocumentIsMutation = (mutation: DocumentNode) => {
const operation = parser(mutation);
invariant(
operation.type === DocumentType.Mutation,
`The <Mutation /> component requires a graphql mutation, but got a ${
operation.type === DocumentType.Query ? 'query' : 'subscription'
}.`,
);
};
private verifyContext = (context: MutationContext) => {
invariant(
!!context.client,
`Could not find "client" in the context of Mutation. Wrap the root component in an <ApolloProvider>`,
);
};
}
export default Mutation;
|