saleor-dashboard/src/mutations.tsx

81 lines
2.4 KiB
TypeScript
Raw Normal View History

2019-08-12 11:48:09 +00:00
import { ApolloError, MutationUpdaterFn } from "apollo-client";
2019-06-19 14:40:52 +00:00
import { DocumentNode } from "graphql";
2019-08-09 10:26:22 +00:00
import React from "react";
2019-08-12 11:48:09 +00:00
import { Mutation, MutationFunction, MutationResult } from "react-apollo";
2019-08-29 10:55:56 +00:00
import { useIntl } from "react-intl";
2019-06-19 14:40:52 +00:00
import useNotifier from "./hooks/useNotifier";
2019-09-04 10:28:04 +00:00
import { commonMessages } from "./intl";
import { getMutationStatus } from "./misc";
2019-12-06 17:14:19 +00:00
import { MutationResultAdditionalProps } from "./types";
2020-05-07 11:04:15 +00:00
import { isJwtError } from "./auth/errors";
import useUser from "./hooks/useUser";
2019-06-19 14:40:52 +00:00
export interface TypedMutationInnerProps<TData, TVariables> {
children: (
2019-08-12 11:48:09 +00:00
mutateFn: MutationFunction<TData, TVariables>,
2019-12-06 17:14:19 +00:00
result: MutationResult<TData> & MutationResultAdditionalProps
2019-06-19 14:40:52 +00:00
) => React.ReactNode;
onCompleted?: (data: TData) => void;
onError?: (error: ApolloError) => void;
variables?: TVariables;
}
2019-08-12 11:48:09 +00:00
// For some reason Mutation returns () => Element instead of () => ReactNode
2019-06-19 14:40:52 +00:00
export function TypedMutation<TData, TVariables>(
mutation: DocumentNode,
update?: MutationUpdaterFn<TData>
) {
return (props: TypedMutationInnerProps<TData, TVariables>) => {
const notify = useNotifier();
2019-08-29 10:55:56 +00:00
const intl = useIntl();
2020-05-07 11:04:15 +00:00
const user = useUser();
2019-08-12 11:48:09 +00:00
const { children, onCompleted, onError, variables } = props;
2019-06-19 14:40:52 +00:00
return (
2019-08-12 11:48:09 +00:00
<Mutation
2019-06-19 14:40:52 +00:00
mutation={mutation}
onCompleted={onCompleted}
2019-09-04 10:28:04 +00:00
onError={(err: ApolloError) => {
if (err.networkError) {
notify({
text: intl.formatMessage(commonMessages.somethingWentWrong)
});
}
2019-10-24 12:10:00 +00:00
if (
err.graphQLErrors[0].extensions.exception?.code ===
"ReadOnlyException"
2019-10-24 12:10:00 +00:00
) {
notify({
text: intl.formatMessage(commonMessages.readOnly)
});
} else if (err.graphQLErrors.some(isJwtError)) {
2020-05-07 11:04:15 +00:00
user.logout();
notify({
text: intl.formatMessage(commonMessages.sessionExpired)
});
2019-10-24 12:10:00 +00:00
} else {
notify({
text: intl.formatMessage(commonMessages.somethingWentWrong)
});
}
2019-06-19 14:40:52 +00:00
if (onError) {
onError(err);
}
}}
variables={variables}
update={update}
>
2019-12-06 17:11:28 +00:00
{(mutateFn, result) => (
<>
{children(mutateFn, {
...result,
2019-12-06 17:17:44 +00:00
status: getMutationStatus(result)
2019-12-06 17:11:28 +00:00
})}
</>
)}
2019-08-12 11:48:09 +00:00
</Mutation>
2019-06-19 14:40:52 +00:00
);
};
}