Skip to content

Instantly share code, notes, and snippets.

@mjurincic
Forked from nodkz/relayStore.js
Created January 28, 2017 16:17
Show Gist options
  • Save mjurincic/ea0c8d740106e32c0e46ed08c578408f to your computer and use it in GitHub Desktop.
Save mjurincic/ea0c8d740106e32c0e46ed08c578408f to your computer and use it in GitHub Desktop.
relayStore with `reset` and simplified `mutate` methods
let relayStore;
function relayCreateStore() {
const env = new Relay.Environment();
env.injectNetworkLayer(new Relay.DefaultNetworkLayer('/graphql'));
if (__DEV__) {
RelayNetworkDebug.init(env);
}
env.reset = () => relayCreateStore();
env.mutate = ({
query,
variables,
collisionKey,
configs,
onSuccess,
onError,
onEnd,
onStart,
optimisticQuery,
optimisticResponse,
optimisticConfigs,
}) => {
// see docs https://facebook.github.io/relay/docs/api-reference-relay-graphql-mutation.html#content
let vars;
if (!variables) {
vars = undefined;
} else {
if (variables.input) { // eslint-disable-line
vars = variables;
} else {
vars = { input: variables };
}
}
if (onStart) {
onStart();
}
let collisionKeyComputed;
if (collisionKey) {
collisionKeyComputed = collisionKey;
} else if (variables) {
// if _id provided, then take it as collision key
if (variables._id) {
collisionKeyComputed = variables._id;
} else if (variables.record && variables.record._id) {
collisionKeyComputed = variables.record._id;
}
}
const mutation = new Relay.GraphQLMutation(
query,
vars,
null, // I don't use file upload, cause upload by signed url directly to S3
relayStore,
{
onFailure: (transaction) => {
if (onError) onError(transaction);
if (onEnd) onEnd();
},
onSuccess: (response) => {
if (onSuccess) onSuccess(response);
if (onEnd) onEnd();
},
},
collisionKeyComputed
);
if (optimisticResponse) {
mutation.applyOptimistic(
optimisticQuery || query, // if optimisticQuery not provided, then take query
optimisticResponse,
optimisticConfigs || configs,
);
}
// we can get transaction here but no need, cause callbacks already defined in constructor
const transaction = mutation.commit(configs);
return mutation;
};
relayStore = env;
return env;
}
relayCreateStore();
export default relayStore;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment